package sisi.enquires;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Bandbox;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Groupbox;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Separator;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Vbox;
import org.zkoss.zul.Window;

import sisi.Configuration;
import sisi.ConfigurationController;
import sisi.General;
import sisi.currency.Currency;
import sisi.invoices.Custinvoice;
import sisi.invoices.CustinvoiceController;
import sisi.invoices.Custinvoicedetail;
import sisi.invoices.CustinvoicedetailController;
import sisi.invoices.Suppinvoice;
import sisi.invoices.SuppinvoiceController;
import sisi.invoices.Suppinvoicedetail;
import sisi.invoices.SuppinvoicedetailController;
import sisi.payment.Payment;
import sisi.payment.PaymentsController;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.status.StatusController;
import sisi.suppliers.Portssupplier;
import sisi.suppliers.Supplier;
import sisi.suppliers.SupplierController;
import sisi.suppliers.Supplierproduct;
import sisi.unitmeasure.Unitmeasure;
import sisi.yacht.Anayacht;
import sisi.yacht.AnayachtController;


/**
 * QuoteToCustomerWindow.java - Controller class for <i>QuoteToCustomer window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 19/5/2014
 * 
 */


@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class QuoteToCustomerWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {
//window
private Window finestraDettaglio, windowEditSupplierNote, windowEditAgentNote, windowRichiestaData;
private Window windowEditDetailNote;
private Window windowAcceptanceQuote;
private Listbox boxDetail; //, boxSuppliers, boxSuppliers2;
private Listbox boxBoatName, boxEnqNumber, boxEnqNumber2;

protected Map<String, Object> args;
// edit
//
private Textbox tbSearchBoatName, tbArt15, tbAgentID, tbAgentName, tbLocation;
private Textbox tbBoatName, tbBoatContact, tbPortToRefuel, tbCountry, tbHowManyRecords;
private Datebox dbDeliveryDate;
private Bandbox bbBoatName, bbEnqNumber, bbEnqNumber2;
private Intbox idBoatName, idEnqNumber, idEnqNumber2;
private Radiogroup rgChoices;
private Button btnLinkSupplier;
private Notesupp notesuppmod;
//
private Intbox ESNid, ESNidSupplier;
private Textbox ESNtbSupplier, ESNNote;
//
private Intbox EANid, EANidAgent;
private Textbox EANtbAgent, EANNote;
//
private Datebox dbData;

// editQ2cSuppSect
private Window windowQ2CSuppSection;
private Intbox rownumber, idproduct, idsupplier;
private Textbox tbProductDesc, tbSupplier, tbActualUM, tbOriginalUM, tbLabelVAT;
private Checkbox cbPhisical, cbTrader;
private Listbox boxUMQuote, boxCurrency;
private Doublebox dbQtyQuote, dbOriginalQty, dbDnty, dbUnitCost, dbNetCost, dbVatPerc;
private Doublebox dbDiscount, dbShipping, dbTotalCost, dbVatUnit, dbVat;
private Doublebox dbCostVatEx, dbCostVat;
private Bandbox bbUMQuote, bbCurrency;
private Textbox tbUMQuote, tbCurrency;
private Textbox tbCustomerNote;

// editQ"CCustSect
private Window windowQ2CCustSection;
private Intbox rownumber2, idproduct2, idcustomer;
private Textbox tbProductDesc2, tbCustomer, tbUMQuoteCust;
private Doublebox dbQtyQuoteCust, dbQtyCustReadOnly, dbUnitCostVat;
private Doublebox dbPriceLTTaxVat, dbPriceLTTax, dbPriceLTVat;
private Doublebox dbPriceUSGTaxVat, dbPriceUSGTax, dbPriceUSGVat;
private Doublebox dbPriceM3TaxVat, dbPriceM3Tax, dbPriceM3Vat;
private Doublebox dbPriceMTTaxVat, dbPriceMTTax, dbPriceMTVat;
private Doublebox dbSaleUnitPriceBlue, dbSaleUnitPriceViolet;

private Radiogroup rgSaleValueIncrement;

private Doublebox dbEarnPerc;
private Doublebox dbSCUnitPriceTaxableVat, dbSCUnitPriceTaxable, dbSCUnitPriceVat, dbCCUnitPriceTaxableVat, dbCCUnitPriceTaxable, dbCCUnitPriceVat;
private Doublebox dbSCTotEarnTaxableVat, dbSCTotEarnTaxable, dbSCTotEarnVat, dbCCTotEarnTaxableVat, dbCCTotEarnTaxable, dbCCTotEarnVat;
private Doublebox dbSCTotSaleTaxableVat, dbSCTotSaleTaxable, dbSCTotSaleVat, dbCCTotSaleTaxableVat, dbCCTotSaleTaxable, dbCCTotSaleVat;
private Doublebox dbPreviousUnitPrice, dbEarnTot, dbExChRate;

private Textbox detailNote;

private Label lblExChRate;



// acceptance quote or confirmations

private Window finestraDettaglio2;
private Combobox cbSupplierSelected;

private Integer sezione = 0;


/*

select reqshipfuelassdetail.id, reqshipfuelass.deliverydt, reqshipfuelass.porttoref, reqshipfuelassdetail.stat, 
anayacht.id, anayacht.name, anayacht.corporation, reqshipfuelass.idportref, anayacht.captain, ports.country, 
reqshipfuelass.agentid, reqshipfuelass.agent, (CASE reqshipfuelass.art15 WHEN true THEN 'yes' ELSE 'no' END) as art15x
from ((anayacht inner join reqshipfuelass on anayacht.id = reqshipfuelass.vesselnameid) 
inner join ports on reqshipfuelass.idportref = ports.id) 
left join (suppliers right join reqshipfuelassdetail on suppliers.supplid = reqshipfuelassdetail.supplierid) on reqshipfuelass.id = reqshipfuelassdetail.id
group by reqshipfuelassdetail.id, reqshipfuelass.deliverydt, reqshipfuelass.porttoref, reqshipfuelassdetail.stat,
 anayacht.id, anayacht.name, anayacht.corporation, reqshipfuelass.idportref, anayacht.captain, ports.country, 
 reqshipfuelass.agentid, reqshipfuelass.agent, (CASE reqshipfuelass.art15 WHEN true THEN 'yes' ELSE 'no' END)
having (((reqshipfuelassdetail.id)>1000) and ((reqshipfuelassdetail.stat)='IQ' or (reqshipfuelassdetail.stat)='QC'))
order by reqshipfuelassdetail.id desc;


*/

		public void onCreate$windowQuoteToCustomer(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();

		/*
		ListModelList listModelListYachts = new ListModelList();
		listModelListYachts.addAll(new AnayachtController().getAnayachtList(null));
		boxBoatName.setModel(listModelListYachts);
		boxBoatName.setItemRenderer(new BoatNameRenderer());
		*/
		
		ListModelList listModelListEnqNumber = new ListModelList();
		listModelListEnqNumber.addAll(new ReqshipfuelassController().getListaEnqNumberIQ_QC());
		boxEnqNumber.setModel(listModelListEnqNumber);
		boxEnqNumber.setItemRenderer(new EnqNumberRenderer());
		bbEnqNumber.setReadonly(false);

		idEnqNumber.setValue(null);

		finestraDettaglio.setVisible(false);
		//bbEnqNumber.setReadonly(true);
		idEnqNumber.setValue(null);
		
		Component tmp = finestraDettaglio.getFellow("boxDetail");
		boxDetail = (Listbox) tmp; 
				
		}

		
	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);
	}

	
	public void onSelect$boxEnqNumber(Event event){
		int iSelected = boxEnqNumber.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oEnqNumber = boxEnqNumber.getItemAtIndex(iSelected).getAttribute("rigaEnqNumber");
		Object[] oRiga = (Object[])oEnqNumber;
		Integer id = (Integer)oRiga[0];
		idEnqNumber.setValue(id);

		finestraDettaglio.setVisible(true);
		viewDettaglio(id);
	}
	
	
	public void onOK$bbEnqNumber(Event event){
		changeORokEnqNumber(event);
	}
	
	public void onChange$bbEnqNumber(Event event){
		changeORokEnqNumber(event); 
	}
	
	private void changeORokEnqNumber(Event event){
		
		if (bbEnqNumber.getValue()==null){
			return;
		}
	
		List lista = new ReqshipfuelassController().getListaEnqNumberIQ_QC();
		
		boolean valido = false;
		for (Object object : lista) {
			Object[] oRiga = (Object[])object;
			Integer id = (Integer)oRiga[0];
			if ( Integer.valueOf( bbEnqNumber.getValue() ).compareTo(id)==0){
				idEnqNumber.setValue(id);
				valido = true;
				break;
			}
		}

		if (!valido){
			Messagebox.show("Enquire number not valid! - "+bbEnqNumber.getValue(), "Information", Messagebox.OK, Messagebox.INFORMATION);
			bbEnqNumber.setValue(null);
			finestraDettaglio.setVisible(false);
			tbAgentID.setValue("");
			tbAgentName.setValue("");
			tbCountry.setValue("");
			tbBoatName.setValue("");
			tbBoatContact.setValue("");
			dbDeliveryDate.setValue(null);
			dbDeliveryDate.setButtonVisible(false);
			tbPortToRefuel.setValue("");			
			tbCountry.setValue("");
			tbArt15.setValue( "NO" );
			
		} else {
			finestraDettaglio.setVisible(true);
			idEnqNumber.setValue(Integer.valueOf( bbEnqNumber.getValue() ));
			viewDettaglio(Integer.valueOf( bbEnqNumber.getValue() ));
		}
	}
		
	private void viewDettaglio(Integer idEnqNumber){
		ListModelList listModelListEnqNumber = new ListModelList();
		listModelListEnqNumber.addAll(new ReqshipfuelassdetailController().getList(idEnqNumber));		
		boxDetail.setModel(listModelListEnqNumber);
		boxDetail.setItemRenderer(new EnqNumberDetailRenderer());
		
		Component tmp = finestraDettaglio.getFellow("tbHowManyRecords");
		tbHowManyRecords = (Textbox) tmp; 
		tbHowManyRecords.setValue("Contains "+listModelListEnqNumber.getSize()+" record/s");
		// aggiorno dati agent id se c'è
		
		tbAgentID.setValue("");
		tbAgentName.setValue("");
		tbCountry.setValue("");
		
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idEnqNumber);
		if (reqshipfuelass.getAgentid()!=null && reqshipfuelass.getAgentid().compareTo(0)!=0){
			tbAgentID.setValue(""+reqshipfuelass.getAgentid());
			tbAgentName.setValue(reqshipfuelass.getAgent());
		}
		
		tbBoatName.setValue(reqshipfuelass.getVesselname());
		tbBoatContact.setValue(reqshipfuelass.getCaptain());
		dbDeliveryDate.setValue(reqshipfuelass.getDeliverydt());
		dbDeliveryDate.setButtonVisible(false);
		tbPortToRefuel.setValue(reqshipfuelass.getPorttoref());
		
		if (reqshipfuelass.getIdportref()!=null && reqshipfuelass.getIdportref()!=0){
			Port porto = new PortController().getPortxId(reqshipfuelass.getIdportref());
			tbCountry.setValue(porto.getCountry());
		}
				
		tbArt15.setValue( (reqshipfuelass.getArt15()==null||!reqshipfuelass.getArt15()?"NO":"SI") );
		
	}
		
		
	
	
	public void onClick$btnCustomerNotes(Event event){
		
		Integer valore = 0;
		
		if ( bbEnqNumber != null ){
			if ( bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty()){
				return;
			}
			valore = Integer.valueOf( bbEnqNumber.getValue() );
		} else if ( bbEnqNumber2 != null ) {
			if ( bbEnqNumber2.getValue()==null || bbEnqNumber2.getValue().isEmpty()){
				return;
			}			
			valore = Integer.valueOf( bbEnqNumber2.getValue() );
		} else {
			return;
		}
		
		Sessions.getCurrent().setAttribute("NoteCustomerIDRequest", valore );
		
		Window finestraCustomerNote = (Window) Executions.createComponents(
				"/editCustomerNote.zul", null, null);
		finestraCustomerNote.doModal();

		Sessions.getCurrent().setAttribute("NoteCustomerIDRequest", null );
		
	}
	
	
	public void onCreate$windowEditCustomerNote(Event event) {

		Integer idRequest = (Integer) Sessions.getCurrent().getAttribute("NoteCustomerIDRequest");	
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idRequest);
		tbCustomerNote.setValue(reqshipfuelass.getNote());
		idEnqNumber.setValue(reqshipfuelass.getId());
	
	}
	
	public void onClose$windowEditCustomerNote(Event event) {
		Integer idRequest = (Integer) Sessions.getCurrent().getAttribute("NoteCustomerIDRequest");	
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idRequest);
		reqshipfuelass.setNote(tbCustomerNote.getValue());
		new ReqshipfuelassController().update(reqshipfuelass);
	}
	
	public void onClick$btnSupplierNotes(Event event){
		int i = boxDetail.getSelectedIndex();
		if (i==-1){
			return;
		}
		Object oDetail = boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
		Reqshipfuelassdetail reqdet = (Reqshipfuelassdetail)oDetail;

		Integer idRequest = reqdet.getId();
		Integer idSupplier = reqdet.getSupplierid();
		if (idSupplier!=null){
			Notesupp notesupp = new NotesuppController().getxIdReqEIdSupplier(idRequest, idSupplier);

			if (notesupp.getId()==null){
				notesupp.setId(idRequest);
				notesupp.setSuppid(idSupplier);
			}
			Sessions.getCurrent().setAttribute("NoteSupplier", notesupp);
			
			Window finestraSupplierNote = (Window) Executions.createComponents(
					"/editSupplierNote.zul", null, null);
			finestraSupplierNote.doModal();
			
			notesuppmod = (Notesupp) Sessions.getCurrent().getAttribute("NoteSupplierMod");
			if (notesuppmod!=null){
				if (notesuppmod.getIdmaster()==null){
					new NotesuppController().add(notesuppmod);
				} else {
					new NotesuppController().update(notesuppmod);
				}
			}
			Sessions.getCurrent().setAttribute("NoteSupplier", null);
			Sessions.getCurrent().setAttribute("NoteSupplierMod", null);
		}
	}
		
	public void onCreate$windowEditSupplierNote(Event event) {

		notesuppmod = (Notesupp) Sessions.getCurrent().getAttribute("NoteSupplier");
		
		Supplier supplier = new SupplierController().getxId(notesuppmod.getSuppid());
		
		ESNid.setValue(notesuppmod.getId());
		ESNidSupplier.setValue(supplier.getSupplid());
		ESNtbSupplier.setValue(supplier.getCompanyname());
		
		ESNNote.setValue(notesuppmod.getNotes());
	
	}	

	public void onClick$btnConferma2(Event event){
		notesuppmod.setNotes(ESNNote.getValue());
		Sessions.getCurrent().setAttribute("NoteSupplierMod", notesuppmod);
		windowEditSupplierNote.detach();
	}
	
	public void onClick$btnAnnulla2(Event event){
		windowEditSupplierNote.detach();
	}
	
	
	
	
	
	public void onClick$btnAgentNotes(Event event){
		
		Integer valore = null;;
		
		if ( bbEnqNumber != null ){
			if ( bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty()){
				return;
			}
			valore = Integer.valueOf( bbEnqNumber.getValue() );
		} else if ( bbEnqNumber2 != null ) {
			if ( bbEnqNumber2.getValue()==null || bbEnqNumber2.getValue().isEmpty()){
				return;
			}			
			valore = Integer.valueOf( bbEnqNumber2.getValue() );
		}
		
		if ( tbAgentID.getValue() == null || tbAgentID.getValue().isEmpty() || valore == null ){
			General.showNotify("You can't edit Agent's note: there is no agent assigned to", null, 4000);
			return;
		}		
		//Integer idRequest = Integer.valueOf( bbEnqNumber.getValue() );

		Sessions.getCurrent().setAttribute("idRequest", valore);
			
		Window finestraAgentNote = (Window) Executions.createComponents(
				"/editAgentNote.zul", null, null);
		finestraAgentNote.doModal();
			
		Sessions.getCurrent().setAttribute("idRequest", null);
			
	}
	
	
	public void onCreate$windowEditAgentNote(Event event) {

		Integer idRequest = (Integer) Sessions.getCurrent().getAttribute("idRequest");
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idRequest);
		
		EANid.setValue(idRequest);
		EANidAgent.setValue(reqshipfuelass.getAgentid());
		EANtbAgent.setValue(reqshipfuelass.getAgent());
		EANNote.setValue(reqshipfuelass.getNotea());
	
	}	

	public void onClick$btnConferma3(Event event){		
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(EANid.getValue());
		reqshipfuelass.setNotea(EANNote.getValue());
		new ReqshipfuelassController().update(reqshipfuelass);
		windowEditAgentNote.detach();
	}
	
	public void onClick$btnAnnulla3(Event event){
		windowEditAgentNote.detach();
	}
	
	public void onClick$btnAgentNomination(Event event){
		Configuration conf = new ConfigurationController().getxId(1);
		EANNote.setValue(conf.getAgentnomination());
	}
	
	public void onClick$btnAgentInformation(Event event){
		Configuration conf = new ConfigurationController().getxId(1);
		EANNote.setValue(conf.getAgentinformation());
	}

	
	public void onClick$btnPrintQuotation(Event event) throws FileNotFoundException, SQLException, JRException {
		printQuotationToTheBoat();
	}
	
	public void onClick$btnPrintAgentNomination(Event event) throws FileNotFoundException, SQLException, JRException {
		
		Integer valore = 0;
		
		if ( bbEnqNumber != null ){
			if ( bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty()){
				return;
			}
			valore = Integer.valueOf( bbEnqNumber.getValue() );
		} else if ( bbEnqNumber2 != null ) {
			if ( bbEnqNumber2.getValue()==null || bbEnqNumber2.getValue().isEmpty()){
				return;
			}			
			valore = Integer.valueOf( bbEnqNumber2.getValue() );
		} else {
			return;
		}
		
		String location = "";
		if (tbLocation!=null){
			location = tbLocation.getValue();
		}
		
		new ReqForAQuoteWindow().printAgentInformationNomination("AgentNomination", valore, tbAgentID, location );
	}
	
	public void onClick$btnPrintAgentInformation(Event event) throws FileNotFoundException, SQLException, JRException {
		new ReqForAQuoteWindow().printAgentInformationNomination("AgentInformation", idEnqNumber.getValue(), tbAgentID, null );
	}
	
	public void onClick$btnBerthAssignement(Event event) throws FileNotFoundException, SQLException, JRException {
		
		Integer valore = 0;
		
		if ( bbEnqNumber != null ){
			if ( bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty()){
				return;
			}
			valore = Integer.valueOf( bbEnqNumber.getValue() );
		} else if ( bbEnqNumber2 != null ) {
			if ( bbEnqNumber2.getValue()==null || bbEnqNumber2.getValue().isEmpty()){
				return;
			}			
			valore = Integer.valueOf( bbEnqNumber2.getValue() );
		} else {
			return;
		}

		new ReqForAQuoteWindow().printBerthAssignment( valore );
	}
	
	private void printQuotationToTheBoat() throws SQLException, JRException, FileNotFoundException {

		if ( bbEnqNumber.getValue() == null || bbEnqNumber.getValue().isEmpty() ){
			General.showNotify("Select a Enquiry number...", null, 4000);
			return; 
		}
		
		// TODO controlli di congruenza
		
		
		
		
		Sessions.getCurrent().setAttribute("richiestaData", null);
		
		Window finestraReqDate = (Window) Executions.createComponents(
				"/richiestaData.zul", null, null);
		finestraReqDate.doModal();
		
		Date data = (Date) Sessions.getCurrent().getAttribute("richiestaData");
		if (data==null){
			return;
		}
		
		Sessions.getCurrent().setAttribute("richiestaData", null);
		
//		Object oSupplier = new Object();//boxSuppliers2.getSelectedItem().getAttribute("rigaSupplier");
//		Supplier supplier = (Supplier) oSupplier;

		
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props);
		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		//params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );
		params.put( "PAR_REQUEST_ID", Integer.valueOf( bbEnqNumber.getValue() ) );
//		params.put( "PAR_SUPPLIER_ID", supplier.getSupplid() );
		params.put( "PAR_DATA", data);

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/QuoteToCust.jasper";
		//System.out.println(fileJasper);
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/QuoteToCust.pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");
		
		List<Reqshipfuelassdetail> detailRSFA = new ReqshipfuelassdetailController().getList(Integer.valueOf( bbEnqNumber.getValue() ));
		for (Reqshipfuelassdetail reqdet : detailRSFA) {
			if (reqdet.getQuoteyesno()!=null && reqdet.getQuoteyesno() && reqdet.getStat().equalsIgnoreCase("IQ") ){
				reqdet.setStat("QC");
				new ReqshipfuelassdetailController().update(reqdet);
			}
		}
		
		viewDettaglio(Integer.valueOf( bbEnqNumber.getValue() ));
		
	}
	
	
	public void onChange$tbLocation(Event event){
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idEnqNumber.getValue());
		reqshipfuelass.setLocation(tbLocation.getValue());
		new ReqshipfuelassController().update(reqshipfuelass);
	}
	
	
	public void onCreate$windowRichiestaData(Event event) {

		dbData.setValue(new Date());

	}	
	
	public void onClick$btnConfermaData(Event event){
		
		Sessions.getCurrent().setAttribute("richiestaData", dbData.getValue());
		windowRichiestaData.detach();
	}
	

	public void onClick$btnAnnullaData(Event event){
		windowRichiestaData.detach();		
	}

	
	public class RendererDetail implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Reqshipfuelassdetail detail = ((Reqshipfuelassdetail) data);
			
			new Listcell(""+detail.getId()).setParent(li);
			new Listcell(""+detail.getSeq()).setParent(li);
			new Listcell(""+detail.getProductid()).setParent(li);
			
			Listcell cellProductname = new Listcell(detail.getProductname());
			cellProductname.setStyle("white-space:nowrap;overflow:hidden");
			cellProductname.setParent(li);
			new Listcell(""+detail.getQuantity()).setParent(li);
			new Listcell(detail.getUm()).setParent(li);
			new Listcell(detail.getStat()).setParent(li);
			Listcell cellNote = new Listcell(""+detail.getNote());
			cellNote.setStyle("white-space:nowrap;overflow:hidden");
			cellNote.setParent(li);
			li.setAttribute("rigaDetail", data);
			
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClickedDetail");
		}
	}

	
	private class BoatNameRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			Anayacht yacht = (Anayacht)data;
			new Listcell(yacht.getName()).setParent(item);
			new Listcell(""+yacht.getId()).setParent(item);
			new Listcell(yacht.getCorporation()).setParent(item);
			item.setAttribute("rigaBoatName", data);
		}
	}
	

	private class EnqNumberRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Object[] oRiga = (Object[])data;
			Integer id = (Integer)oRiga[0];

			Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(id);

			//Port port = new PortController().getPortxId(reqshipfuelass.getIdportref());
			
			new Listcell(""+id).setParent(item);
			new Listcell(""+reqshipfuelass.getPorttoref()).setParent(item);
			new Listcell(""+reqshipfuelass.getStatus()).setParent(item);
			new Listcell(""+reqshipfuelass.getVesselnameid()).setParent(item);
			new Listcell(""+reqshipfuelass.getVesselname()).setParent(item);
			new Listcell(""+reqshipfuelass.getAgentid()).setParent(item);
			item.setAttribute("rigaEnqNumber", data);
		}
	}

	
	private class EnqNumberRendererAcceptanceQuote implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Object[] oRiga = (Object[])data;
			Integer id = (Integer)oRiga[0];

			Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(id);

			//Port port = new PortController().getPortxId(reqshipfuelass.getIdportref());
			
			new Listcell(""+id).setParent(item);
			new Listcell(""+reqshipfuelass.getVesselnameid()).setParent(item);
			new Listcell(""+reqshipfuelass.getVesselname()).setParent(item);
			new Listcell(""+ General.formatoFecha( reqshipfuelass.getDeliverydt() ) ).setParent(item);
			new Listcell(""+reqshipfuelass.getPorttoref()).setParent(item); 
			new Listcell(""+reqshipfuelass.getAgentid()).setParent(item);
			item.setAttribute("rigaEnqNumber", data);
		}
	}
	
	private class SuppliersProductItemRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Supplierproduct supplierProduct = (Supplierproduct)data;

			
			new Listcell(""+supplierProduct.getSupname()).setParent(item);
			new Listcell(""+supplierProduct.getSupid()).setParent(item);
			item.setAttribute("rigaSupplier", data);
		}
	}

	private class PortSuppliersItemRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Portssupplier portsupplier = (Portssupplier)data;
			
			Supplier supplier = new SupplierController().getxId(portsupplier.getSuppid());
			
			
			new Listcell(""+supplier.getCompanyname()).setParent(item);
			new Listcell(""+supplier.getSupplid()).setParent(item);
			item.setAttribute("rigaSupplier", data);
		}
	}
	
	
	private class Suppliers2ItemRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Supplier supplier = (Supplier)data;
			
			new Listcell(""+supplier.getCompanyname()).setParent(item);
			item.setAttribute("rigaSupplier", data);
		}
	}
	
	private class EnqNumberDetailRenderer implements ListitemRenderer {
	
		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			/*
			Object[] oRiga = (Object[])data;
			Integer id = (Integer)oRiga[0];
			Integer idSeq = (Integer)oRiga[1];
			Integer idMaster = (Integer)oRiga[15];
			Integer idSupplier = (Integer)oRiga[13];
			*/
			
			Reqshipfuelassdetail reqshipfuelassdetail = (Reqshipfuelassdetail)data;


			Textbox tbIdEnq = new Textbox(""+reqshipfuelassdetail.getId());
			tbIdEnq.setWidth("50px");
			tbIdEnq.setReadonly(true);

			//+ " of "+ General.paddingString(""+boxDetail.getModel().getSize(), 2, '0', true )
			Textbox tbRowNumber = new Textbox("" + General.paddingString(""+reqshipfuelassdetail.getSeq(), 2, '0', true) );
			tbRowNumber.setWidth("30px");
			tbRowNumber.setReadonly(true);
					
			Textbox tbProductName = new Textbox(reqshipfuelassdetail.getProductname());
			tbProductName.setWidth("200px");
			tbProductName.setRows(2);
			tbProductName.setReadonly(true);
			
			Textbox tbProductId = new Textbox(""+reqshipfuelassdetail.getProductid());
			tbProductId.setWidth("60px");
			tbProductId.setReadonly(true);
			
			Textbox tbQuantity = new Textbox( General.decimalFormat("#,##0.000", reqshipfuelassdetail.getQuantity()) );
			tbQuantity.setWidth("80px");
			tbQuantity.setStyle("text-align: right;");
			tbQuantity.setReadonly(true);
			
			Textbox tbUM = new Textbox(""+reqshipfuelassdetail.getUm());
			tbUM.setWidth("40px");
			tbUM.setReadonly(true);

			Textbox tbCodStatus = new Textbox(""+reqshipfuelassdetail.getStat());
			tbCodStatus.setWidth("40px");
			tbCodStatus.setReadonly(true);

			Textbox tbDesStatus = new Textbox(""+new StatusController().getXCodice(reqshipfuelassdetail.getStat(), false).getDescription() );
			tbDesStatus.setWidth("200px");
			tbDesStatus.setReadonly(true);

			
			Label lblNote = new Label("Note");
			lblNote.setStyle("color:blue");
			
			String note = reqshipfuelassdetail.getNote();
			note = (note==null?"":note);
			Textbox tbRigaNota = new Textbox(""+note);
			tbRigaNota.setWidth("200px");
			tbRigaNota.setReadonly(true);
			tbRigaNota.setRows(4);
			tbRigaNota.setCols(25);

			Label lblSupplier = new Label("Supplier: ");
			lblSupplier.setStyle("color:blue");
			String supplierName = "";
			if (reqshipfuelassdetail.getSupplierid()!=null){
				Supplier supplier = new SupplierController().getxId(reqshipfuelassdetail.getSupplierid());
				
				if (supplier!=null){
					supplierName = supplier.getCompanyname();
				}
			}
			Textbox tbSupplier = new Textbox(supplierName);
			tbSupplier.setWidth("240px");
			tbSupplier.setReadonly(true);
			
			
			final Integer idMasterDetail = reqshipfuelassdetail.getIdmaster();
			
			Combobox cbSupplier = new Combobox();
			cbSupplier.setWidth("50px");
			cbSupplier.setReadonly(true);
			List<Reqquote> reqquoteList = new ReqquoteController().getListxIdReqEreqseq(reqshipfuelassdetail.getId(), reqshipfuelassdetail.getSeq());
			Integer iSelected = 0;
			for (int i = 0; i < reqquoteList.size(); i++) {
				Reqquote reqquote = reqquoteList.get(i);
				if (reqquote.getSuppid()!=null && reqquote.getSuppid()!=0 && reqshipfuelassdetail.getSupplierid()!=null && reqshipfuelassdetail.getSupplierid() != 0 && reqquote.getSuppid().intValue() == reqshipfuelassdetail.getSupplierid() ){
					iSelected = i;
				}				
			}

			
			ListModelList listModelList = new ListModelList();
			listModelList.addAll(reqquoteList);
			
			if (reqquoteList.size()>0){
				listModelList.addToSelection(listModelList.get(iSelected));
			}
			
			cbSupplier.setModel(listModelList);
			cbSupplier.setItemRenderer(new SupplierItemRenderer());

			cbSupplier.addEventListener("onSelect", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
				
					List<Component> listaChilds = event.getTarget().getParent().getChildren();
					Textbox tbDescSupplier = (Textbox)event.getTarget().getParent().getLastChild();
					Textbox tbIdSupplier = (Textbox)listaChilds.get(0);
					Combobox co = (Combobox) componente;
					tbDescSupplier.setValue(co.getSelectedItem().getDescription());
					tbIdSupplier.setValue(co.getSelectedItem().getLabel());
					
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					reqdet.setSupplierid( Integer.valueOf( co.getSelectedItem().getLabel()) );
					new ReqshipfuelassdetailController().update(reqdet);	
				}
				});			

			Label lblSequenceNote = new Label("Sequence Note");
			lblSequenceNote.setStyle("color:blue");
			
			String sequenceNote = "";
			Boolean tbReadOnly = true;
			
			if (reqshipfuelassdetail.getSupplierid()!=null){
				tbReadOnly = false;
				Notesuppseqt notesupp = new NotesuppseqtController().getxIdReqEIdSupplier(reqshipfuelassdetail.getId(), reqshipfuelassdetail.getSupplierid(), reqshipfuelassdetail.getSeq() );
				if (notesupp!=null){
					sequenceNote = notesupp.getNote();
				}
			}

			Textbox tbSequenceNote = new Textbox(sequenceNote);
			tbSequenceNote.setWidth("200px");
			tbSequenceNote.setReadonly(tbReadOnly);
			tbSequenceNote.setRows(4);
			tbSequenceNote.setCols(25);
			
			tbSequenceNote.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					final InputEvent evt = (InputEvent) event;
					String valore = evt.getValue();
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent()).getIndex();
					Object oRigaDetail = boxDetail.getItemAtIndex(iIndex).getAttribute("rigaEnqDetailNumber");
	
					
					Object[] oRiga = (Object[])oRigaDetail;
					Integer id = (Integer)oRiga[0];
					Integer idSeq = (Integer)oRiga[1];
					Integer idSupplier = (Integer)oRiga[13];
					
					Notesuppseqt notesuppseqt = new NotesuppseqtController().getxIdReqEIdSupplier(id, idSupplier, idSeq);
					if (notesuppseqt.getId()==null){ // insert
						notesuppseqt.setIdrequest(id);
						notesuppseqt.setIdsupplier(idSupplier);
						notesuppseqt.setSeq(idSeq);
						notesuppseqt.setNote(valore);
						new NotesuppseqtController().add(notesuppseqt);
					} else { // update
						notesuppseqt.setNote(valore);
						new NotesuppseqtController().update(notesuppseqt);
					}
				}
			});

			
			Textbox tbIdSupplier = new Textbox(""+(reqshipfuelassdetail.getSupplierid()==null?"":reqshipfuelassdetail.getSupplierid()));
			tbIdSupplier.setWidth("40px");
			tbIdSupplier.setReadonly(true);
			tbIdSupplier.setVisible(false);
			
			
			// Purchase
			Textbox tbSuppCurrency = new Textbox(""+ (reqshipfuelassdetail.getSuppcurr()==null||reqshipfuelassdetail.getSuppcurr().isEmpty() ? "" : reqshipfuelassdetail.getSuppcurr() ) );
			tbSuppCurrency.setWidth("30px");
			tbSuppCurrency.setReadonly(true);

			Textbox tbSuppUM =  new Textbox(""+( reqshipfuelassdetail.getSuppumquote()==null || reqshipfuelassdetail.getSuppumquote().isEmpty() ? "" : reqshipfuelassdetail.getSuppumquote() ) );
			tbSuppUM.setWidth("30px");
			tbSuppUM.setReadonly(true);
			
			Textbox tbSuppUnitPrice =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getSuppnetunitcost() ) );
			tbSuppUnitPrice.setWidth("70px");
			tbSuppUnitPrice.setReadonly(true);
			tbSuppUnitPrice.setStyle("text-align: right;"); 

			Textbox tbSuppNetTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getSuppnetcost() ) );
			tbSuppNetTotal.setWidth("80px");
			tbSuppNetTotal.setReadonly(true);
			tbSuppNetTotal.setStyle("text-align: right;");
			
			Label lblQuoteDt = new Label("QuoteDt");
			lblQuoteDt.setStyle("color:blue");

			Textbox tbSuppQty =  new Textbox(""+General.decimalFormat("#,##0.000", reqshipfuelassdetail.getSuppqtyquote() ) );
			tbSuppQty.setWidth("70px");
			tbSuppQty.setReadonly(true);
			tbSuppQty.setStyle("text-align: right;");

			Label lblSuppVAT = new Label("VAT");
			lblSuppVAT.setStyle("color:black");
			
			Textbox tbSuppVat =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getSuppvat() ) );
			tbSuppVat.setWidth("60px");
			tbSuppVat.setReadonly(true);
			tbSuppVat.setStyle("text-align: right;");

			
			//Textbox tbSuppQuoteDt =  new Textbox(""+General.formatoFecha( reqshipfuelassdetail.getQuotedt() ) );
			//tbSuppQuoteDt.setWidth("120px");
			//tbSuppQuoteDt.setReadonly(true);
			
			// modificare con un datebox 11/5/2015
			Datebox dbSuppQuoteDt =  new Datebox();
			dbSuppQuoteDt.setValue( reqshipfuelassdetail.getQuotedt() );
			dbSuppQuoteDt.setFormat("dd/MM/yyyy hh:mm");
			dbSuppQuoteDt.setWidth("120px");
		
			dbSuppQuoteDt.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) { 
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					Datebox db = (Datebox)componente;
					
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					if (!reqdet.getStat().equalsIgnoreCase("IQ")){
						db.setValue(reqdet.getQuotedt());
						General.showNotify("You can't update this control: order status = "+reqdet.getStat(), null, 3000);
					} else {
						reqdet.setQuotedt( (db.getText().isEmpty() ? null : General.date2SqlTimestamp( db.getValue() ) ) );
						new ReqshipfuelassdetailController().update(reqdet);
						
						Object oDetail = boxDetail.getItemAtIndex(iIndex).getAttribute("rigaEnqDetailNumber");						
						Reqshipfuelassdetail reqdet2 = (Reqshipfuelassdetail)oDetail;
						reqdet2.setQuotedt( reqdet.getQuotedt() );
						
						ListModelList lml = (ListModelList) boxDetail.getListModel();

						if (lml.indexOf(reqdet2) != -1) {
							lml.set(lml.indexOf(reqdet2), reqdet2);
						}
						
						General.showNotify("Quote Dt updated...", null, 1000);
					}
					
				}
					
			});
			
			
			Button btnSupplier = new Button();
			btnSupplier.setLabel("Supplier");
			
			btnSupplier.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					
					Sessions.getCurrent().setAttribute("idSelected", iIndex);
					
					editQ2CSuppSect(idMasterDetail);
					
				}
					
			});

			
			Label lblSuppTotal = new Label("TOTAL");
			lblSuppTotal.setStyle("color:black");

			Textbox tbSuppTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getSupptotalcost() ) );
			tbSuppTotal.setWidth("80px");
			tbSuppTotal.setReadonly(true);
			tbSuppTotal.setStyle("text-align: right;");

			Label lblSuppDelMethod = new Label("Del Method");
			lblSuppDelMethod.setStyle("color:black");

			Textbox tbSuppDelMethod =  new Textbox(""+ ( reqshipfuelassdetail.getDeliverymethod()==null || reqshipfuelassdetail.getDeliverymethod().isEmpty() ? "": reqshipfuelassdetail.getDeliverymethod() ) );
			tbSuppDelMethod.setWidth("250px");
			tbSuppDelMethod.setReadonly(false);
			tbSuppDelMethod.setMaxlength(15);
			
			tbSuppDelMethod.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					final InputEvent evt = (InputEvent) event;
					String valore = evt.getValue();
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					//Object oRigaDetail = boxDetail.getItemAtIndex(iIndex).getAttribute("rigaEnqDetailNumber");					
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					//Object[] oRiga = (Object[])oRigaDetail;
					//Integer id = (Integer)oRiga[0];
					
					Reqshipfuelassdetail rigaDetail = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					rigaDetail.setDeliverymethod(valore);
					
					new ReqshipfuelassdetailController().update(rigaDetail);
					
					General.showNotify("Delivery method updated...", null, 1000);

				}
			});
			
			
			

			Checkbox cbSuppQuote = new Checkbox("Quote?");
			//cbSuppQuote.setDisabled(true);
			final Boolean checked = (reqshipfuelassdetail.getQuoteyesno()==null ? false : reqshipfuelassdetail.getQuoteyesno() ) ;
			cbSuppQuote.setChecked(checked);
			
			cbSuppQuote.addEventListener("onCheck", new EventListener() {
				public void onEvent(Event event) { 
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					Checkbox cb = (Checkbox)componente;
					
					//Sessions.getCurrent().setAttribute("idSelected", iIndex);
					//editQ2CSuppSect(idMasterDetail);
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					if (!reqdet.getStat().equalsIgnoreCase("IQ")){
						cb.setChecked(checked);
						General.showNotify("You can't update this control: order status = "+reqdet.getStat(), null, 3000);
					} else {
						reqdet.setQuoteyesno(cb.isChecked());
						reqdet.setQuotedt( General.date2SqlTimestamp( new java.util.Date() ) );						
						//tbSuppQuoteDt.setValue( General.formatoFecha( reqdet.getQuotedt() ) );				
						new ReqshipfuelassdetailController().update(reqdet);
						
						Object oDetail = boxDetail.getItemAtIndex(iIndex).getAttribute("rigaEnqDetailNumber");						
						Reqshipfuelassdetail reqdet2 = (Reqshipfuelassdetail)oDetail;
						reqdet2.setQuotedt( General.date2SqlTimestamp( new java.util.Date() ) );
						reqdet2.setQuoteyesno(cb.isChecked());
						
						ListModelList lml = (ListModelList) boxDetail.getListModel();

						if (lml.indexOf(reqdet2) != -1) {
							lml.set(lml.indexOf(reqdet2), reqdet2);
						}
						
						General.showNotify("Quote updated...", null, 1000);
					}
					
				}
					
			});
			
			// Sale
			
			Textbox tbCustCurrency = new Textbox(""+reqshipfuelassdetail.getCurr());
			tbCustCurrency.setWidth("30px");
			tbCustCurrency.setReadonly(true);

			Textbox tbCustUM =  new Textbox(""+(reqshipfuelassdetail.getCustum()==null?"":reqshipfuelassdetail.getCustum()));
			tbCustUM.setWidth("30px");
			tbCustUM.setReadonly(true);
			
			Textbox tbCustUnitPrice =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getCustnetunitcost() ) );
			tbCustUnitPrice.setWidth("70px");
			tbCustUnitPrice.setReadonly(true);
			tbCustUnitPrice.setStyle("text-align: right;");

			Textbox tbCustNetTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getCustnetcost() ) );
			tbCustNetTotal.setWidth("80px");
			tbCustNetTotal.setReadonly(true);
			tbCustNetTotal.setStyle("text-align: right;");

			Textbox tbCustEarnPerc =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getEarn() ) + " %" );
			tbCustEarnPerc.setWidth("50px");
			tbCustEarnPerc.setReadonly(true);
			tbCustEarnPerc.setStyle("text-align: right;");	
			
			Label lblCustExChRate = new Label("ExChRate");
			lblCustExChRate.setStyle("color:black");

			
			
			Textbox tbCustQty =  new Textbox(""+General.decimalFormat("#,##0.000", reqshipfuelassdetail.getCustqtyquote() ) );
			tbCustQty.setWidth("60px");
			tbCustQty.setReadonly(true);
			tbCustQty.setStyle("text-align: right;");

			Label lblCustVAT = new Label("VAT");
			lblCustVAT.setStyle("color:black");
			
			Textbox tbCustVat =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getCustvat() ) );
			tbCustVat.setWidth("60px");
			tbCustVat.setReadonly(true);
			tbCustVat.setStyle("text-align: right;");

			Textbox tbCustEartTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getTotearn() ) );
			tbCustEartTotal.setWidth("60px");
			tbCustEartTotal.setReadonly(true);
			tbCustEartTotal.setStyle("text-align: right;");

			Textbox tbCustExChRate =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getExchrate()) );
			tbCustExChRate.setWidth("60px");
			tbCustExChRate.setReadonly(true);
			tbCustExChRate.setStyle("text-align: right; color: red;");

			
			Button btnCustomer = new Button();
			btnCustomer.setLabel("Customer");
			
			btnCustomer.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					
					Sessions.getCurrent().setAttribute("idSelected", iIndex);
					
					editQ2CCustSect(idMasterDetail);
					
				}
					
			});
			
			
			
			Label lblCustTotal = new Label("TOTAL");
			lblCustTotal.setStyle("color:black");

			Textbox tbCustTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getCusttotsalevat() ) );
			tbCustTotal.setWidth("80px"); 
			tbCustTotal.setReadonly(true);
			tbCustTotal.setStyle("text-align: right;");
			
			Button btnCustDetailNote = new Button();
			btnCustDetailNote.setLabel("Detail Note");
			
			btnCustDetailNote.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					
					Sessions.getCurrent().setAttribute("idSelected", iIndex);
					
					editQ2CDetailNote(idMasterDetail);
					
				}
					
			});
			
			
			Label lblCustStatus = new Label("Status");
			lblCustStatus.setStyle("color:black");
			
			Textbox tbCustStatus =  new Textbox(""+reqshipfuelassdetail.getStat());
			tbCustStatus.setWidth("40px"); 
			tbCustStatus.setReadonly(true);
			tbCustStatus.setStyle("text-align: center; color:red;");

			Label lblCustCustInvoice = new Label("CustInvoice");
			lblCustCustInvoice.setStyle("color:black");
			
			Textbox tbCustCustInvoice =  new Textbox(""+(reqshipfuelassdetail.getCustinvoicenumber()==null?"":reqshipfuelassdetail.getCustinvoicenumber()));
			tbCustCustInvoice.setWidth("40px"); 
			tbCustCustInvoice.setReadonly(true);
			tbCustCustInvoice.setStyle("text-align: left;");

			Label lblCustSuppInvoice = new Label("SuppInvoice");
			lblCustSuppInvoice.setStyle("color:black");
			
			String custSuppInvoice = reqshipfuelassdetail.getSuppinvoicenumber();
			custSuppInvoice = (custSuppInvoice==null || custSuppInvoice.isEmpty()?"":custSuppInvoice);
			Textbox tbCustSuppInvoice =  new Textbox(""+custSuppInvoice);
			tbCustSuppInvoice.setWidth("40px"); 
			tbCustSuppInvoice.setReadonly(true);
			tbCustSuppInvoice.setStyle("text-align: left;");
			
			Textbox tbCustCustInvoiceStatus =  new Textbox("");
			tbCustCustInvoiceStatus.setWidth("40px"); 
			tbCustCustInvoiceStatus.setReadonly(true);
			tbCustCustInvoiceStatus.setStyle("text-align: left;");
			
			Custinvoicedetail custinvoicedetail = new CustinvoicedetailController().getCustinvoicedetail(reqshipfuelassdetail.getProductname(), reqshipfuelassdetail.getId());
			if (custinvoicedetail!=null){
				tbCustCustInvoice.setValue(""+(custinvoicedetail.getCustnuminvoice()==null?"":custinvoicedetail.getCustnuminvoice()));
				tbCustCustInvoiceStatus.setValue(custinvoicedetail.getStat());
			}
			
			Textbox tbCustSuppInvoiceStatus =  new Textbox("");
			tbCustSuppInvoiceStatus.setWidth("40px"); 
			tbCustSuppInvoiceStatus.setReadonly(true);
			tbCustSuppInvoiceStatus.setStyle("text-align: left;"); 
			
			Suppinvoicedetail suppinvoicedetail = new SuppinvoicedetailController().getSuppinvoicedetail(reqshipfuelassdetail.getProductname(), reqshipfuelassdetail.getId());
			if (suppinvoicedetail!=null){
				tbCustSuppInvoice.setValue(""+(suppinvoicedetail.getSuppnuminvoice()==null?"":suppinvoicedetail.getSuppnuminvoice()));
				tbCustSuppInvoiceStatus.setValue(suppinvoicedetail.getStat());
			}

			
			Separator separator = new Separator();
			separator.setWidth("20px");			
			
			Hbox hbox00 = new Hbox();
			Hbox hboxa1 = new Hbox();
			Hbox hboxa2 = new Hbox();
			Hbox hboxa3 = new Hbox();
			Hbox hboxb1 = new Hbox();
			Hbox hboxb2 = new Hbox();
			Hbox hboxb3 = new Hbox();
			Hbox hboxb4 = new Hbox();
			Hbox hboxc1 = new Hbox();
			Hbox hboxc2 = new Hbox();
			Hbox hboxc3 = new Hbox();
			Hbox hboxc4 = new Hbox();
			//
			Vbox vbox3 = new Vbox();
			Hbox hboxc5 = new Hbox();
			Hbox hboxc6 = new Hbox();
			
			Groupbox gbox1 = new Groupbox();
			Groupbox gbox2 = new Groupbox();
			Groupbox gbox3 = new Groupbox();
			Groupbox gbox3b = new Groupbox();
			//gbox3b.setStyle("border-color: red;");
			gbox3b.setContentStyle("border: 2px solid red; padding 3px");
			
			hboxa2.setPack("end");
			hboxa2.setAlign("end");
			
			hboxa1.appendChild(tbIdEnq);
			hboxa1.appendChild(tbRowNumber);	
			hboxa1.appendChild(tbProductName);
			hboxa2.appendChild(lblSupplier);
			hboxa3.appendChild(tbIdSupplier);
			hboxa3.appendChild(cbSupplier);
			hboxa2.appendChild(tbUM);
			hboxa2.appendChild(tbQuantity);
			hboxa3.appendChild(tbSupplier);
			//
			hboxb1.appendChild(tbSuppCurrency);
			hboxb1.appendChild(tbSuppUM);
			hboxb1.appendChild(tbSuppUnitPrice);
			hboxb1.appendChild(tbSuppNetTotal); 
			hboxb1.appendChild(lblQuoteDt);
			hboxb2.appendChild(tbSuppQty);
			separator = new Separator();
			separator.setWidth("50px");
			hboxb2.appendChild( separator );
			hboxb2.appendChild(lblSuppVAT);
			separator = new Separator();
			separator.setWidth("17px");	
			hboxb2.appendChild( separator );
			hboxb2.appendChild(tbSuppVat); 
			hboxb2.appendChild(dbSuppQuoteDt);
			
			hboxb3.appendChild(btnSupplier);
			separator = new Separator();
			separator.setWidth("50px");
			hboxb3.appendChild( separator );	
			hboxb3.appendChild(lblSuppTotal);
			hboxb3.appendChild(tbSuppTotal);
			hboxb4.appendChild(lblSuppDelMethod);
			hboxb4.appendChild(tbSuppDelMethod);
			hboxb4.appendChild(cbSuppQuote);
			//
			hboxc1.appendChild(tbCustCurrency);
			hboxc1.appendChild(tbCustUM);
			hboxc1.appendChild(tbCustUnitPrice);
			hboxc1.appendChild(tbCustNetTotal);
			hboxc1.appendChild(tbCustEarnPerc);
			hboxc1.appendChild(lblCustExChRate);
			
			hboxc2.appendChild(tbCustQty);
			separator = new Separator();
			separator.setWidth("55px");
			hboxc2.appendChild(separator);
			hboxc2.appendChild(lblCustVAT);
			separator = new Separator();
			separator.setWidth("20px");
			hboxc2.appendChild(separator);
			hboxc2.appendChild(tbCustVat);
			hboxc2.appendChild(tbCustEartTotal);
			hboxc2.appendChild(tbCustExChRate);
			
			hboxc3.appendChild(btnCustomer);
			separator = new Separator();
			separator.setWidth("40px");
			hboxc3.appendChild(separator);
			hboxc3.appendChild(lblCustTotal);
			hboxc3.appendChild(tbCustTotal);
			
			hboxc4.appendChild(btnCustDetailNote);
			hboxc4.appendChild(lblCustStatus);
			hboxc4.appendChild(tbCustStatus);
			
			hboxc5.appendChild(lblCustCustInvoice);
			hboxc5.appendChild(tbCustCustInvoice);
			hboxc5.appendChild(tbCustCustInvoiceStatus);
			
			hboxc6.appendChild(lblCustSuppInvoice);
			hboxc6.appendChild(tbCustSuppInvoice);
			hboxc6.appendChild(tbCustSuppInvoiceStatus); 
			
			vbox3.appendChild(hboxc5);
			vbox3.appendChild(hboxc6);
			gbox3b.appendChild(vbox3);
			
			hboxc4.appendChild(gbox3b);
			
			gbox1.appendChild(hboxa1);
			gbox1.appendChild(hboxa2);
			gbox1.appendChild(hboxa3);
			//
			gbox2.appendChild(hboxb1);
			gbox2.appendChild(hboxb2);
			gbox2.appendChild(hboxb3);
			gbox2.appendChild(hboxb4); 
			//
			gbox3.appendChild(hboxc1);
			gbox3.appendChild(hboxc2);
			gbox3.appendChild(hboxc3);
			gbox3.appendChild(hboxc4);
			
			hbox00.appendChild(gbox1);
			hbox00.appendChild(gbox2);
			hbox00.appendChild(gbox3);
			
			gbox1.setHeight("128px");
			
			Listcell listcell = new Listcell();
			
			listcell.appendChild(hbox00);
			
			listcell.setParent(item);
			
			item.setAttribute("rigaEnqDetailNumber", data);

		}
	}
	
	private void updateTBField( Textbox field, String valore ){
		field.setValue(valore);
	}
	
	
	private class SupplierItemRenderer implements ComboitemRenderer {
		
		@Override
		public void render(Comboitem item, Object data, int index)
				throws Exception {
			
			Reqquote su = (Reqquote)data;
			item.setLabel(""+su.getSuppid());
			item.setDescription(su.getSupname());			
		}


	}
	
	// EDIT SUPPLIER'S SECTION
	public void onCreate$windowQ2CSuppSection(Event event) {

		
		sezione = 1; // supplier's section
		
		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		Integer idMasterDetail = (Integer)Sessions.getCurrent().getAttribute("idMasterDetail");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		idEnqNumber.setValue(reqdet.getId());
		rownumber.setValue(reqdet.getSeq());
		idproduct.setValue(reqdet.getProductid());
		tbProductDesc.setValue(reqdet.getProductname());
		idsupplier.setValue(reqdet.getSupplierid());
		
		if (idsupplier.getValue()!=null){
			Supplier supplier = new SupplierController().getxId(idsupplier.getValue());
			tbSupplier.setValue(supplier.getCompanyname());
		}
		
		//tbSupplier.setValue(reqdet.get)
		cbPhisical.setChecked(reqdet.getPhistraderId()!=null && reqdet.getPhistraderId()==1);

		//cbTrader.setChecked(reqdet.getsupp)
		// listbox unita di misura
		
		tbActualUM.setValue( (reqdet.getSuppumquote()==null?"":reqdet.getSuppumquote() ) );
		bbUMQuote.setValue(tbActualUM.getValue());
		dbQtyQuote.setValue(reqdet.getSuppqtyquote());
		dbOriginalQty.setValue(reqdet.getQuantity());
		dbDnty.setValue(reqdet.getDnty());
		
		tbOriginalUM.setValue(reqdet.getUm());
		dbUnitCost.setValue(reqdet.getSuppunitcost());
		dbNetCost.setValue(reqdet.getSuppnetunitcost());
		dbVatPerc.setValue(reqdet.getSuppvatperc());
		dbVat.setValue(reqdet.getSuppvat());
		
		dbDiscount.setValue(reqdet.getDiscount());
		
		dbShipping.setValue(reqdet.getShipping());
		
		// listbox unità di misure
	
		ListModelList listModelList = new ListModelList();
		listModelList.addAll(new sisi.unitmeasure.UnitmeasureController().getUnitmeasureList(null));
		boxUMQuote.setModel(listModelList);
		boxUMQuote.setItemRenderer(new UnitMeasureRenderer()); 
		
		// listbox currency	
		ListModelList listModelList2 = new ListModelList();
		List<Currency> listaCurrency = new sisi.currency.CurrencyController().getList(null);
		listModelList2.addAll(listaCurrency);
		boxCurrency.setModel(listModelList2);
		boxCurrency.setItemRenderer(new CurrencyRenderer());
		
		if (reqdet.getSuppcurr()!=null && !reqdet.getSuppcurr().isEmpty()){
			bbCurrency.setValue(reqdet.getSuppcurr());
			for (int i = 0; i < listaCurrency.size(); i++) {
				Currency cu = (Currency)listaCurrency.get(i);
				if (cu.getCurr().equalsIgnoreCase(reqdet.getSuppcurr())){
					boxCurrency.setSelectedIndex(i);
					break;
				}
			}
		}
		
		aggSuppValues();
			
	}
	
	
	private class UnitMeasureRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Unitmeasure um = (Unitmeasure)data;
			
			new Listcell(""+um.getUm()).setParent(item);
			new Listcell(""+um.getDescum()).setParent(item);
			item.setAttribute("rigaUnitmeasure", data);
		}
	}
	
	public class CurrencyRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Currency cu = (Currency)data;
			
			new Listcell(""+cu.getCurr()).setParent(item);
			new Listcell(""+cu.getCurrdesc()).setParent(item);
			item.setAttribute("rigaCurrency", data);
		}
	}
	
	private void aggSuppValues(){
		
		
		if (sezione==2){
			aggCustValues();
			return;
		}
		
		Double qtyQuote = General.doubleZeroNull( dbQtyQuote.getValue() );
		Double unitCost = General.doubleZeroNull( dbUnitCost.getValue() );
		Double netCost = General.doubleZeroNull( dbNetCost.getValue() );
		Double percVAT = General.doubleZeroNull( dbVatPerc.getValue() );
		Double discount = General.doubleZeroNull( dbDiscount.getValue() );
		Double shipping = General.doubleZeroNull( dbShipping.getValue() );
		Double totalCost = General.doubleZeroNull( dbTotalCost.getValue() );
		Double unitVat = General.doubleZeroNull( dbVatUnit.getValue() );
		Double totalVAT = General.doubleZeroNull( dbVat.getValue() );
		Double netCostVATex = General.doubleZeroNull( dbCostVatEx.getValue() );
		Double netTotCostVATex = General.doubleZeroNull( dbCostVat.getValue() ); 
		
		dbVatPerc.setValue(percVAT);
		
		netCost = unitCost - unitCost * discount / 100;
		dbNetCost.setValue(netCost);
		
		unitVat = netCost - netCost / ( 1 + ( percVAT / 100 ) );
		dbVatUnit.setValue(unitVat);
		
		totalVAT = qtyQuote * unitVat;
		dbVat.setValue(totalVAT);
		
		netCostVATex = netCost - unitVat;
		dbCostVatEx.setValue(netCostVATex);
		
		netTotCostVATex = netCostVATex * qtyQuote;
		dbCostVat.setValue(netTotCostVATex);
		
		totalCost = netCost * qtyQuote;
		dbTotalCost.setValue(totalCost);
		
		tbLabelVAT.setValue("V.A.T. "+percVAT+"%");
		
	}
	
	public void onChange$dbQtyQuote(){
		aggSuppValues();
	}
	
	public void onChange$dbUnitCost(){
		aggSuppValues();
	}
	
	public void onChange$dbDiscount(){
		aggSuppValues();
	}
	
	public void onChange$dbVatPerc(){
		aggSuppValues();
	}
	
	public void onChange$dbShipping(){
		aggSuppValues();
	}
	
	public void onClick$btnSaveRecordSupplierSection(){
		Integer idMasterDetail = (Integer)Sessions.getCurrent().getAttribute("idMasterDetail");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
				
		reqdet.setSuppumquote( bbUMQuote.getValue() );
		reqdet.setSuppqtyquote( dbQtyQuote.getValue() );
		reqdet.setDnty( dbDnty.getValue()==null || dbDnty.getValue().equals(new Double(0))? new Double(1) :  dbDnty.getValue() );
		reqdet.setSuppunitcost( dbUnitCost.getValue() );
		//reqdet.setSuppnetcost( dbNetCost.getValue() );
		reqdet.setSuppvat( dbVat.getValue() );
		reqdet.setSuppvatperc(dbVatPerc.getValue());
		reqdet.setDiscount( dbDiscount.getValue() );
		reqdet.setShipping(dbShipping.getValue());
		reqdet.setSuppcurr(bbCurrency.getValue());
		reqdet.setSupptotalcost(dbTotalCost.getValue());
		
		reqdet.setSuppnetcost( dbCostVat.getValue() ); // 25/3/2015
		reqdet.setSuppunitvat(dbVatUnit.getValue()); // 25/3/2015
		reqdet.setSuppnetunitcost(dbNetCost.getValue()-dbVatUnit.getValue()); // 25/3/2015 netunitdisc - unit vat
		reqdet.setSuppunitcostdisc(dbNetCost.getValue()); // 25/3/2015

		new ReqshipfuelassdetailController().update(reqdet);
		General.showNotify( "Updating...", null);
		
		windowQ2CSuppSection.detach();
		
	}
	
	private void editQ2CSuppSect(Integer idMasterDetail){
			
		Sessions.getCurrent().setAttribute("idMasterDetail", idMasterDetail);
		
		Window finestraEditQ2CSuppSect = (Window) Executions.createComponents(
				"/editQ2CSuppSection.zul", null, null);
		finestraEditQ2CSuppSect.doModal();
		
		Integer iIndex = (Integer)Sessions.getCurrent().getAttribute("idSelected");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		ListModelList lml = (ListModelList) boxDetail.getListModel();
		lml.set(iIndex, reqdet);
		
	}

	
	
	
	
	// EDIT CUSTOMER'S SECTION
	
	private void editQ2CCustSect(Integer idMasterDetail){
		
		Sessions.getCurrent().setAttribute("idMasterDetail", idMasterDetail);
		
		Window finestraEditQ2CSuppSect = (Window) Executions.createComponents(
				"/editQ2CCustSection.zul", null, null);
		finestraEditQ2CSuppSect.doModal();
		
		Integer iIndex = (Integer)Sessions.getCurrent().getAttribute("idSelected");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		ListModelList lml = (ListModelList) boxDetail.getListModel();
		lml.set(iIndex, reqdet);
		
	}
	
	
	public void onCreate$windowQ2CCustSection(Event event) {

		sezione = 2; // customer's section
		
		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		Integer idMasterDetail = (Integer)Sessions.getCurrent().getAttribute("idMasterDetail");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		idEnqNumber.setValue(reqdet.getId());
		rownumber.setValue(reqdet.getSeq());
		idproduct.setValue(reqdet.getProductid());
		tbProductDesc.setValue(reqdet.getProductname());
		idsupplier.setValue(reqdet.getSupplierid());
		
		if (idsupplier.getValue()!=null){
			Supplier supplier = new SupplierController().getxId(idsupplier.getValue());
			tbSupplier.setValue(supplier.getCompanyname());
		}
		
		tbCurrency.setValue(reqdet.getSuppcurr());
		dbVatPerc.setValue(reqdet.getSuppvatperc());
		tbUMQuote.setValue(reqdet.getSuppumquote());

		dbNetCost.setValue(reqdet.getSuppnetunitcost()); // 25/3/2015		
		//double netCost = reqdet.getSuppnetunitcost(); // 25/3/2015
		//double percVAT = reqdet.getSuppvatperc();
		//double unitVat = netCost - netCost / ( 1 + ( percVAT / 100 ) );
		dbVatUnit.setValue(reqdet.getSuppunitvat());

		dbQtyQuote.setValue(reqdet.getSuppqtyquote()); 
		dbOriginalQty.setValue(reqdet.getQuantity());
		dbDnty.setValue(reqdet.getDnty());
		tbOriginalUM.setValue(reqdet.getUm());
		
		dbQtyCustReadOnly.setValue(reqdet.getSuppqtyquote());
		dbEarnPerc.setValue(reqdet.getEarn());
		dbEarnTot.setValue(reqdet.getTotearn());
			
		// listbox unità di misure
		
		//bbUMQuote.setValue(reqdet.getUm());
		bbUMQuote.setValue(reqdet.getCustum());
		
		ListModelList listModelList = new ListModelList();
		List<Unitmeasure> listaUM = new sisi.unitmeasure.UnitmeasureController().getUnitmeasureList(null);
		listModelList.addAll(listaUM);
		boxUMQuote.setModel(listModelList);
		boxUMQuote.setItemRenderer(new UnitMeasureRenderer());
		
		boxUMQuote.addEventListener("onClick", new EventListener() {
			public void onEvent(Event event) {
				aggCustValues();
			}
		});

				
		if (reqdet.getCustum()!=null && !reqdet.getCustum().isEmpty()){
			for (int i = 0; i < listaUM.size(); i++) {
				Unitmeasure um = (Unitmeasure)listaUM.get(i);
				if (um.getUm().equalsIgnoreCase(reqdet.getCustum())){
					boxUMQuote.setSelectedIndex(i);
					break;
				}
			}
		}
		
		double unitCostVat = General.doubleZeroNull(reqdet.getSuppnetunitcost())+General.doubleZeroNull(reqdet.getSuppunitvat());
		dbUnitCostVat.setValue(unitCostVat);
		
		//
		idEnqNumber2.setValue(reqdet.getId());
		rownumber2.setValue(reqdet.getSeq());
		idproduct2.setValue(reqdet.getProductid());
		tbProductDesc2.setValue(reqdet.getProductname());
		
		Reqshipfuelass reqship = new ReqshipfuelassController().getxId(reqdet.getId());
		idcustomer.setValue(reqship.getVesselnameid());
		tbCustomer.setValue(reqship.getVesselname());
		
		Double exChRate = reqdet.getExchrate();
		exChRate = ( exChRate == null || exChRate.compareTo(new Double(0))==0 ? 1.00 : exChRate );

		dbExChRate.setValue( exChRate );
		
		// listbox currency	
		ListModelList listModelList2 = new ListModelList();
		List<Currency> listaCurrency = new sisi.currency.CurrencyController().getList(null);
		listModelList2.addAll(listaCurrency);
		boxCurrency.setModel(listModelList2);
		boxCurrency.setItemRenderer(new CurrencyRenderer());
		
		boxCurrency.addEventListener("onClick", new EventListener() {
			public void onEvent(Event event) {
				aggCustValues();
			}
		});
		
		if (reqdet.getCurr()!=null && !reqdet.getCurr().isEmpty()){
			bbCurrency.setValue(reqdet.getCurr());
			for (int i = 0; i < listaCurrency.size(); i++) {
				Currency cu = (Currency)listaCurrency.get(i);
				if (cu.getCurr().equalsIgnoreCase(reqdet.getCurr())){
					boxCurrency.setSelectedIndex(i);
					break;
				}
			}
		} 
		dbQtyQuoteCust.setValue(reqdet.getCustqtyquote());
		
		dbTotalCost.setValue(reqdet.getSupptotalcost());
		dbCostVat.setValue(reqdet.getSuppvat());
		dbCostVatEx.setValue(reqdet.getSuppnetcost());
		
		dbSCUnitPriceTaxable.setReadonly(true);
		dbEarnPerc.setReadonly(true); 
		
		dbPreviousUnitPrice.setValue(reqdet.getCustnetunitcost());
		dbSaleUnitPriceBlue.setValue(reqdet.getCustnetunitcost());
		

		//changeRgSaleValueIncrement();
		aggCustValues(); // chiamato in automatico dalla funzione precedente
		
		dbCCUnitPriceTaxable.setValue(reqdet.getCustnetunitcost());
		rgSaleValueIncrement.setSelectedIndex(1);
		dbSCUnitPriceTaxable.setReadonly(false);
		dbCCUnitPriceTaxable.setReadonly(false);
		
		aggCustValues(2);
			
	}

	private void aggCustValues(){
		
		if (sezione==1){
			aggSuppValues();
			return;
		}
		
		Double netCost = dbUnitCostVat.getValue();
		Double costVAT = dbVatUnit.getValue();
		Double density = dbDnty.getValue();
		density = (density==null||density.compareTo(Double.valueOf("0"))==0?1:density);

		Double priceLTTaxVat = 0.00, priceLTTax = 0.00, priceLTVat = 0.00;
		Double priceUSGTaxVat = 0.00, priceUSGTax = 0.00, priceUSGVat = 0.00;
		Double priceM3TaxVat = 0.00, priceM3Tax = 0.00, priceM3Vat = 0.00;
		Double priceMTTaxVat = 0.00, priceMTTax = 0.00, priceMTVat = 0.00;

		Double suppVatPerc = General.doubleZeroNull( dbVatPerc.getValue() );
		Double exChRate = dbExChRate.getValue();
		exChRate = ( exChRate == null || exChRate.compareTo(new Double(0))==0 ? 1.00 : exChRate );
		
		// se valute uguali
		if (tbCurrency.getValue().trim().compareTo(bbCurrency.getValue().trim())==0){
			exChRate = 1.00;
			dbExChRate.setValue(exChRate);
		}
		
		lblExChRate.setValue("ExChRate "+tbCurrency.getValue()+"/"+bbCurrency.getValue());
		
		if (tbUMQuote.getValue().equalsIgnoreCase("LT")){
			
			priceLTTaxVat = netCost;
			priceLTVat = costVAT;
			
			priceUSGTaxVat = priceLTTaxVat * 3.7854;	
			priceUSGVat = priceLTVat * 3.7854 ;

			
			priceM3TaxVat = priceLTTaxVat * 1000;
			priceM3Vat = priceLTVat * 1000;
			
			priceMTTaxVat = priceLTTaxVat / density * 1000; 
			priceMTVat = priceLTVat / density * 1000;
			
			
		} else if (tbUMQuote.getValue().equalsIgnoreCase("USG")){
			
			priceUSGTaxVat = netCost;
			priceUSGVat = costVAT;
			
			priceLTTaxVat = priceUSGTaxVat / 3.7854;
			priceLTVat = priceUSGVat / 3.7854;		
			
			priceM3TaxVat = priceLTTaxVat * 1000;
			priceM3Vat = priceLTVat * 1000;
			
			priceMTTaxVat = priceLTTaxVat / density * 1000; 
			priceMTVat = priceLTVat / density * 1000;		
			
		} else if (tbUMQuote.getValue().equalsIgnoreCase("M3")){
			
			priceM3TaxVat = netCost;
			priceM3Vat = costVAT;
			
			priceLTTaxVat = priceM3TaxVat / 1000;
			priceLTVat = priceM3Vat / 1000;
			
			priceUSGTaxVat = priceLTTaxVat * 3.7854;
			priceUSGVat = priceLTVat * 3.7854 ;
			
			priceMTTaxVat = priceLTTaxVat / density * 1000;
			priceMTVat = priceLTVat / density * 1000;		
			
		} else if (tbUMQuote.getValue().equalsIgnoreCase("MT")){
			
			priceMTTaxVat = netCost;
			priceMTVat = costVAT;
			
			priceLTTaxVat = priceMTTaxVat * density / 1000;
			priceLTVat = priceMTTax * density / 1000;
			
			priceUSGTaxVat = priceLTTaxVat * 3.7854;
			priceUSGVat = priceLTVat * 3.7854 ;
			
			priceM3TaxVat = priceLTTaxVat * 1000;
			priceM3Vat = priceLTVat * 1000;
			
		}
		
		priceLTTax = priceLTTaxVat - priceLTVat;
		priceUSGTax = priceUSGTaxVat - priceUSGVat;
		priceM3Tax = priceM3TaxVat - priceM3Vat;
		priceMTTax = priceMTTaxVat - priceMTVat;
		
		dbPriceLTTaxVat.setValue(priceLTTaxVat);
		dbPriceLTTax.setValue(priceLTTax);
		dbPriceLTVat.setValue(priceLTVat);
		dbPriceUSGTaxVat.setValue(priceUSGTaxVat);
		dbPriceUSGTax.setValue(priceUSGTax);
		dbPriceUSGVat.setValue(priceUSGVat);
		dbPriceM3TaxVat.setValue(priceM3TaxVat);
		dbPriceM3Tax.setValue(priceM3Tax);
		dbPriceM3Vat.setValue(priceM3Vat);
		dbPriceMTTaxVat.setValue(priceMTTaxVat);
		dbPriceMTTax.setValue(priceMTTax);
		dbPriceMTVat.setValue(priceMTVat);

		//
		String umQuote = bbUMQuote.getValue();
		
		/*
		 
		dbSCUnitPriceTaxableVat, dbSCUnitPriceTaxable, dbSCUnitPriceVat, dbCCUnitPriceTaxableVat, dbCCUnitPriceTaxable, dbCCUnitPriceVat;
		dbSCTotEarnTaxableVat, dbSCTotEarnTaxable, dbSCTotEarnVat, dbCCTotEarnTaxableVat, dbCCTotEarnTaxable, dbCCTotEarnVat;
		dbSCTotSaleTaxableVat, dbSCTotSaleTaxable, dbSCTotSaleVat, dbCCTotSaleTaxableVat, dbCCTotSaleTaxable, dbCCTotSaleVat;

		  
		 */
		
		// applicate earn attivo
		if ( rgSaleValueIncrement.getSelectedIndex() == 0 ) {
		
			if (umQuote.equalsIgnoreCase("LT")){
				dbSCUnitPriceTaxableVat.setValue(dbPriceLTTaxVat.getValue());
				dbSCUnitPriceTaxable.setValue(dbPriceLTTax.getValue());
				dbSCUnitPriceVat.setValue(dbPriceLTVat.getValue());
			} else if (umQuote.equalsIgnoreCase("USG")){
				dbSCUnitPriceTaxableVat.setValue(dbPriceUSGTaxVat.getValue());
				dbSCUnitPriceTaxable.setValue(dbPriceUSGTax.getValue());
				dbSCUnitPriceVat.setValue(dbPriceUSGVat.getValue());
			} else if (umQuote.equalsIgnoreCase("M3")){
				dbSCUnitPriceTaxableVat.setValue(dbPriceM3TaxVat.getValue());
				dbSCUnitPriceTaxable.setValue(dbPriceM3Tax.getValue());
				dbSCUnitPriceVat.setValue(dbPriceM3Vat.getValue());
			} else if (umQuote.equalsIgnoreCase("MT")){
				dbSCUnitPriceTaxableVat.setValue(dbPriceMTTaxVat.getValue());
				dbSCUnitPriceTaxable.setValue(dbPriceMTTax.getValue());
				dbSCUnitPriceVat.setValue(dbPriceMTVat.getValue());
			}
			
		// applicate manual attivo
		} else if ( rgSaleValueIncrement.getSelectedIndex() == 1 ){
			
			if ( (dbPreviousUnitPrice.getValue()==null || dbPreviousUnitPrice.getValue().compareTo(new Double(0))==0 ) 
					&& (dbSCUnitPriceTaxable.getValue()==null || dbSCUnitPriceTaxable.getValue().compareTo(new Double(0))==0 )  ){
				// propongo prezzi d'accordo al unità di misura
				if (umQuote.equalsIgnoreCase("LT")){
					dbSCUnitPriceTaxableVat.setValue(dbPriceLTTaxVat.getValue());
					dbSCUnitPriceTaxable.setValue(dbPriceLTTax.getValue());
					dbSCUnitPriceVat.setValue(dbPriceLTVat.getValue());
				} else if (umQuote.equalsIgnoreCase("USG")){
					dbSCUnitPriceTaxableVat.setValue(dbPriceUSGTaxVat.getValue());
					dbSCUnitPriceTaxable.setValue(dbPriceUSGTax.getValue());
					dbSCUnitPriceVat.setValue(dbPriceUSGVat.getValue());
				} else if (umQuote.equalsIgnoreCase("M3")){
					dbSCUnitPriceTaxableVat.setValue(dbPriceM3TaxVat.getValue());
					dbSCUnitPriceTaxable.setValue(dbPriceM3Tax.getValue());
					dbSCUnitPriceVat.setValue(dbPriceM3Vat.getValue());
				} else if (umQuote.equalsIgnoreCase("MT")){
					dbSCUnitPriceTaxableVat.setValue(dbPriceMTTaxVat.getValue());
					dbSCUnitPriceTaxable.setValue(dbPriceMTTax.getValue());
					dbSCUnitPriceVat.setValue(dbPriceMTVat.getValue());
				}
			} else {
				if (dbSCUnitPriceTaxable.getValue()==null || dbSCUnitPriceTaxable.getValue().compareTo(new Double(0))==0 ){
					dbSCUnitPriceTaxable.setValue(dbPreviousUnitPrice.getValue());					
				}
			}
			
			
			// valori del customer
			Double unitPriceCSTaxableVat = 0.00, priceCSTaxable = 0.00, priceCSVat = 0.00;
			if (umQuote.equalsIgnoreCase("LT")){
				unitPriceCSTaxableVat = dbPriceLTTaxVat.getValue();
				priceCSTaxable = dbPriceLTTax.getValue();
				priceCSVat = dbPriceLTVat.getValue();
			} else if (umQuote.equalsIgnoreCase("USG")){
				unitPriceCSTaxableVat = dbPriceUSGTaxVat.getValue();
				priceCSTaxable = dbPriceUSGTax.getValue();
				priceCSVat = dbPriceUSGVat.getValue();
			} else if (umQuote.equalsIgnoreCase("M3")){
				unitPriceCSTaxableVat = dbPriceM3TaxVat.getValue();
				priceCSTaxable = dbPriceM3Tax.getValue();
				priceCSVat = dbPriceM3Vat.getValue();
			} else if (umQuote.equalsIgnoreCase("MT")){
				unitPriceCSTaxableVat = dbPriceMTTaxVat.getValue();
				priceCSTaxable = dbPriceMTTax.getValue();
				priceCSVat = dbPriceMTVat.getValue();
			} else {
				unitPriceCSTaxableVat = dbPriceLTTaxVat.getValue();
				priceCSTaxable = dbPriceLTTax.getValue();
				priceCSVat = dbPriceLTVat.getValue();				
			}
			
			
			// supplier's currency
			
			// unit price
			Double scUnitPriceTaxableVat =  General.doubleZeroNull( dbSCUnitPriceTaxable.getValue() );
			Double scQtyQuoteCust = General.doubleZeroNull( dbQtyQuoteCust.getValue() );
		
			Double scUnitPriceVat = scUnitPriceTaxableVat * suppVatPerc / 100;
			scUnitPriceTaxableVat = scUnitPriceTaxableVat + scUnitPriceTaxableVat * suppVatPerc / 100;
			dbSCUnitPriceTaxableVat.setValue(scUnitPriceTaxableVat);
			dbSCUnitPriceVat.setValue(scUnitPriceVat);
			
			
			
			// total sale
			if (dbQtyQuoteCust.getValue()==null){
				General.showNotify("Quantity Quote to Customer is null", null, 2000, "error");
				return;
			}
			
			if (bbUMQuote.getValue()==null || bbUMQuote.getValue().isEmpty()){
				General.showNotify("Unit Measure Quote (UMQuote) is null", null, 2000, "error");
				return;				
			}
 			
			// values in supplier's currency
			Double totSCTotSaleTaxable = dbSCUnitPriceTaxable.getValue()*dbQtyQuoteCust.getValue();
			dbSCTotSaleTaxable.setValue(totSCTotSaleTaxable);
			dbSCTotSaleTaxableVat.setValue(totSCTotSaleTaxable + totSCTotSaleTaxable * suppVatPerc / 100 );
			dbSCTotSaleVat.setValue(totSCTotSaleTaxable * suppVatPerc / 100);

			
			
			// tot earn 
			//Double totEarnTaxable = dbSCUnitPriceTaxable.getValue() * dbQtyQuote.getValue() - dbCostVatEx.getValue();
			Double costi = dbCostVatEx.getValue(); // 25/3/2015 dbQtyQuote.getValue() * dbNetCost.getValue(); 
			Double vendita = dbSCTotSaleTaxable.getValue();// 25/3/2015 // scUnitPriceTaxableVat * scQtyQuoteCust * exChRate;
			Double guadagno = (vendita - costi);
			Double totEarnTaxable = (vendita - costi); // 11/4/2015  / exChRate;
			Double percEarn = guadagno * 100 / costi;
			
			dbEarnPerc.setValue(percEarn);
			
			dbSCTotEarnTaxable.setValue(totEarnTaxable);

			dbSCTotEarnTaxableVat.setValue(dbSCTotEarnTaxable.getValue() + dbSCTotEarnTaxable.getValue() * suppVatPerc / 100 );
			dbSCTotEarnVat.setValue(dbSCTotEarnTaxable.getValue() * suppVatPerc / 100);

			
			Double unitPriceBlue = dbSCUnitPriceTaxable.getValue();
			dbSaleUnitPriceBlue.setValue(unitPriceBlue);
			
			dbEarnTot.setValue(dbSCTotEarnTaxable.getValue());
			
			// customer's currency
			
			// valute diverse
			if (exChRate!=null ) { // (tbCurrency.getValue().trim().compareTo(bbCurrency.getValue().trim())!=0){
				
				// unit price
				dbCCUnitPriceTaxable.setValue(dbSCUnitPriceTaxable.getValue()*exChRate);
				dbCCUnitPriceTaxableVat.setValue(dbSCUnitPriceTaxableVat.getValue()*exChRate);
				dbCCUnitPriceVat.setValue(dbSCUnitPriceVat.getValue()*exChRate);
				
				// tot earn
				dbCCTotEarnTaxable.setValue(dbSCTotEarnTaxable.getValue()*exChRate);
				dbCCTotEarnTaxableVat.setValue(dbSCTotEarnTaxableVat.getValue()*exChRate);
				dbCCTotEarnVat.setValue(dbSCTotEarnVat.getValue()*exChRate);
				
				// total sale
				dbCCTotSaleTaxable.setValue(dbSCTotSaleTaxable.getValue()*exChRate);
				dbCCTotSaleTaxableVat.setValue(dbSCTotSaleTaxableVat.getValue()*exChRate);
				dbCCTotSaleVat.setValue(dbSCTotSaleVat.getValue()*exChRate);
				
				Double unitPriceViolet = dbCCUnitPriceTaxable.getValue();
				dbSaleUnitPriceViolet.setValue(unitPriceViolet);
				
			}
			
			
			
		// no choices
		} else { 
			
			
		}
		
	}
	
	
	private void aggCustValues(Integer provenienza){
		
		// provenienza
		//== 1 Taxable value (Supplier's Currency)
		//== 2 Taxable value (Customer's Currency)
		//== null 
		

		Double priceLTTaxVat = 0.00, priceLTTax = 0.00, priceLTVat = 0.00;
		Double priceUSGTaxVat = 0.00, priceUSGTax = 0.00, priceUSGVat = 0.00;
		Double priceM3TaxVat = 0.00, priceM3Tax = 0.00, priceM3Vat = 0.00;
		Double priceMTTaxVat = 0.00, priceMTTax = 0.00, priceMTVat = 0.00;

		dbSCUnitPriceTaxable.setValue( dbSCUnitPriceTaxable.getValue()==null ? 0.00 : dbSCUnitPriceTaxable.getValue() );
		
		Double suppVatPerc = General.doubleZeroNull( dbVatPerc.getValue() );
		Double exChRate = dbExChRate.getValue();
		exChRate = ( exChRate == null || exChRate.compareTo(new Double(0))==0 ? 1.00 : exChRate );
		
		Double netCost = dbUnitCostVat.getValue(); 
		Double costVAT = dbVatUnit.getValue();
		Double density = dbDnty.getValue();
		density = (density==null||density.compareTo(Double.valueOf("0"))==0?1:density);
		
		// se valute uguali
		if (tbCurrency.getValue().trim().compareTo(bbCurrency.getValue().trim())==0){
			exChRate = 1.00;
			dbExChRate.setValue(exChRate);
		}
		
		lblExChRate.setValue("ExChRate "+tbCurrency.getValue()+"/"+bbCurrency.getValue());

		if (provenienza==2){
			netCost = dbCCUnitPriceTaxable.getValue();
			netCost = (netCost==null?0:netCost);
			netCost = netCost / exChRate;
			dbSCUnitPriceTaxable.setValue(netCost);
		}
		//

		
		// supplier's currency
		
		// unit price
		Double scUnitPriceTaxableVat =  General.doubleZeroNull( dbSCUnitPriceTaxable.getValue() );
		Double scQtyQuoteCust = General.doubleZeroNull( dbQtyQuoteCust.getValue() );
	
		Double scUnitPriceVat = scUnitPriceTaxableVat * suppVatPerc / 100;
		scUnitPriceTaxableVat = scUnitPriceTaxableVat + scUnitPriceTaxableVat * suppVatPerc / 100;
		dbSCUnitPriceTaxableVat.setValue(scUnitPriceTaxableVat);
		dbSCUnitPriceVat.setValue(scUnitPriceVat);
		
		
		// total sale // 25/3/2015
		Double totSCTotSaleTaxable = dbSCUnitPriceTaxable.getValue()*dbQtyQuoteCust.getValue();
		dbSCTotSaleTaxable.setValue(totSCTotSaleTaxable);
		dbSCTotSaleTaxableVat.setValue(totSCTotSaleTaxable + totSCTotSaleTaxable * suppVatPerc / 100 );
		dbSCTotSaleVat.setValue(totSCTotSaleTaxable * suppVatPerc / 100);
		
		// tot earn 
		//Double totEarnTaxable = dbSCUnitPriceTaxable.getValue() * dbQtyQuote.getValue() - dbCostVatEx.getValue();
		Double costi = dbCostVatEx.getValue(); // 25/3/2015 dbQtyQuote.getValue() * dbNetCost.getValue();
		Double vendita = dbSCTotSaleTaxable.getValue(); // 25/3/2015 scUnitPriceTaxableVat * scQtyQuoteCust * exChRate;
		Double guadagno = (vendita - costi);
		Double totEarnTaxable = (vendita - costi) / exChRate;
		Double percEarn = guadagno * 100 / costi;
		
		dbEarnPerc.setValue(percEarn);
		
		dbSCTotEarnTaxable.setValue(totEarnTaxable);

		dbSCTotEarnTaxableVat.setValue(dbSCTotEarnTaxable.getValue() + dbSCTotEarnTaxable.getValue() * suppVatPerc / 100 );
		dbSCTotEarnVat.setValue(dbSCTotEarnTaxable.getValue() * suppVatPerc / 100);

		
		Double unitPriceBlue = dbSCUnitPriceTaxable.getValue();
		dbSaleUnitPriceBlue.setValue(unitPriceBlue);
		
		dbEarnTot.setValue(dbSCTotEarnTaxable.getValue());
			
		// customer's currency
		
		// valute diverse
		if (exChRate!=null ) { // (tbCurrency.getValue().trim().compareTo(bbCurrency.getValue().trim())!=0){
			
			// unit price
			dbCCUnitPriceTaxable.setValue(dbSCUnitPriceTaxable.getValue()*exChRate);
			dbCCUnitPriceTaxableVat.setValue(dbSCUnitPriceTaxableVat.getValue()*exChRate);
			dbCCUnitPriceVat.setValue(dbSCUnitPriceVat.getValue()*exChRate);
			
			// tot earn
			dbCCTotEarnTaxable.setValue(dbSCTotEarnTaxable.getValue()*exChRate);
			dbCCTotEarnTaxableVat.setValue(dbSCTotEarnTaxableVat.getValue()*exChRate);
			dbCCTotEarnVat.setValue(dbSCTotEarnVat.getValue()*exChRate);
			
			// total sale
			dbCCTotSaleTaxable.setValue(dbSCTotSaleTaxable.getValue()*exChRate);
			dbCCTotSaleTaxableVat.setValue(dbSCTotSaleTaxableVat.getValue()*exChRate);
			dbCCTotSaleVat.setValue(dbSCTotSaleVat.getValue()*exChRate);
			
			Double unitPriceViolet = dbCCUnitPriceTaxable.getValue();
			dbSaleUnitPriceViolet.setValue(unitPriceViolet);
			
		}				
		
	}
	
	public void onCheck$rgSaleValueIncrement(){
		changeRgSaleValueIncrement();
	}
	
	private void changeRgSaleValueIncrement(){
		// applicate earn attivo
		if ( rgSaleValueIncrement.getSelectedIndex() == 0 ) {
				dbSCUnitPriceTaxable.setReadonly(true);
				dbCCUnitPriceTaxable.setReadonly(true);
				dbEarnPerc.setReadonly(false);
			
		// applicate manual attivo
		} else if ( rgSaleValueIncrement.getSelectedIndex() == 1 ){
			dbSCUnitPriceTaxable.setReadonly(false);
			dbCCUnitPriceTaxable.setReadonly(false);
			dbEarnPerc.setReadonly(true); 			
			
		// no choices
		} else { 
			dbSCUnitPriceTaxable.setReadonly(true);
			dbCCUnitPriceTaxable.setReadonly(true);
			dbEarnPerc.setReadonly(true);
		}
		
		aggCustValues();		
	}
	
	public void onChange$dbDnty(){
		aggCustValues();
	}
	
	public void onOK$dbDnty(){
		aggCustValues();
	}
	
	public void onChange$bbUMQuote(){ 
		aggCustValues();
	}	
	public void onChange$bbCurrency(){
		aggCustValues();
	}
	
	public void onChange$dbEarnPerc(){
		aggCustValues();
	}
	
	public void onChange$dbQtyQuoteCust(){
		aggCustValues();
	}
	public void onOK$dbQtyQuoteCust(){
		aggCustValues();
	}
	
	public void onChange$dbExChRate(){
		aggCustValues();
	}
	public void onOK$dbExChRate(){
		aggCustValues();
	}
	
	public void onChange$dbSCUnitPriceTaxable(){
		aggCustValues(1);
	}
	
	public void onOK$dbSCUnitPriceTaxable(){
		aggCustValues(1);
	}
	
	public void onChange$dbCCUnitPriceTaxable(){
		aggCustValues(2);
	}
	
	public void onOK$dbCCUnitPriceTaxable(){
		aggCustValues(2);
	}
	
	
	public void onClick$btnSaveRecordCustomerSection(){
		
		if (bbCurrency.getValue()==null || bbCurrency.getValue().isEmpty()){
			General.showNotify("Currency is empty!!!", null, 3000, "error");
			bbCurrency.setFocus(true);
			return;
		}
		if (bbUMQuote.getValue()==null || bbUMQuote.getValue().isEmpty()){
			General.showNotify("Unit Measure is empty!!!", null, 3000, "error");
			bbUMQuote.setFocus(true);
			return;			
		}
		if (dbQtyQuoteCust.getValue()==null || dbQtyQuoteCust.getValue().compareTo(0.00)==0){
			General.showNotify("Quantity quote is empty!!!", null, 3000, "error");
			dbQtyQuoteCust.setFocus(true);
			return;			
		}
		
		
		
		Integer idMasterDetail = (Integer)Sessions.getCurrent().getAttribute("idMasterDetail");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		rgSaleValueIncrement.setSelectedIndex(1);
		aggCustValues();
		
		reqdet.setDnty( dbDnty.getValue()==null || dbDnty.getValue().equals(new Double(0))? new Double(1) :  dbDnty.getValue() );
		
		reqdet.setExchrate(dbExChRate.getValue());
		reqdet.setCustqtyquote(dbQtyQuoteCust.getValue());
		reqdet.setCustum(bbUMQuote.getValue());
		reqdet.setCurr(bbCurrency.getValue());
		reqdet.setEarn(dbEarnPerc.getValue());
		reqdet.setUnitprice(dbSaleUnitPriceBlue.getValue());
		reqdet.setTotearn(dbEarnTot.getValue());
				
		// da rivedere tutti questi campi
		reqdet.setCustvat(dbCCTotSaleVat.getValue());
		reqdet.setCustnetcost(dbCCTotSaleTaxable.getValue());
		reqdet.setCustunitvat(dbCCUnitPriceVat.getValue());
		reqdet.setCustnetunitcost(dbCCUnitPriceTaxable.getValue());
		reqdet.setCustvatperc(General.doubleZeroNull( dbVatPerc.getValue() ));
		reqdet.setCusttotsalevat(dbCCTotSaleTaxableVat.getValue());
		
		reqdet.setPrreqvess(dbSaleUnitPriceViolet.getValue()); 
		reqdet.setTotsale(dbCCTotSaleTaxable.getValue());
				
		new ReqshipfuelassdetailController().update(reqdet);
		General.showNotify( "Updating...", null);
		
		windowQ2CCustSection.detach();
	}
	
	private void editQ2CDetailNote(Integer idMasterDetail){
		
		Sessions.getCurrent().setAttribute("idMasterDetail", idMasterDetail);
		
		Window finestraEditQ2CDetailNote = (Window) Executions.createComponents(
				"/editDetailNote.zul", null, null);
		finestraEditQ2CDetailNote.doModal();
		
		/*
		Integer iIndex = (Integer)Sessions.getCurrent().getAttribute("idSelected");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		ListModelList lml = (ListModelList) boxDetail.getListModel();
		lml.set(iIndex, reqdet);
		*/
		
	}
	
	public void onCreate$windowEditDetailNote(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		Integer idMasterDetail = (Integer)Sessions.getCurrent().getAttribute("idMasterDetail");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		idEnqNumber.setValue(reqdet.getId());
		rownumber.setValue(reqdet.getSeq());
		detailNote.setValue(reqdet.getNote());
		
	}
	
	public void onClick$btnConferma4(){
		
		Integer idMasterDetail = (Integer)Sessions.getCurrent().getAttribute("idMasterDetail");
		Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
		
		reqdet.setNote(detailNote.getValue());
		
		new ReqshipfuelassdetailController().update(reqdet);
		General.showNotify( "Updating...", null);
		
		windowEditDetailNote.detach();
	
	}
	
	public void onClick$btnAnnulla4(){
		windowEditDetailNote.detach();	
	}

	
	
	/*
	 * 
	 * 
	 * 
	 *  PROCEDURE PURCHASE ORDER CONFIRMATION / ACCEPTANCE QUOTE
	 * 
	 * 
	 * 
	 */

	
	public void onCreate$windowAcceptanceQuote(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
	
		
		ListModelList listModelListEnqNumber = new ListModelList();
		listModelListEnqNumber.addAll(new ReqshipfuelassController().getListaEnqNumberQC_SC_CC_HI());
		boxEnqNumber2.setModel(listModelListEnqNumber);
		boxEnqNumber2.setItemRenderer(new EnqNumberRendererAcceptanceQuote());
		bbEnqNumber2.setReadonly(false);
	
		idEnqNumber.setValue(null);
	
		finestraDettaglio2.setVisible(false);
		//bbEnqNumber.setReadonly(true);
		idEnqNumber.setValue(null);
		
		Component tmp = finestraDettaglio2.getFellow("boxDetail");
		boxDetail = (Listbox) tmp; 
		
	}
	
	
	public void onSelect$boxEnqNumber2(Event event){
		int iSelected = boxEnqNumber2.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oEnqNumber = boxEnqNumber2.getItemAtIndex(iSelected).getAttribute("rigaEnqNumber");
		Object[] oRiga = (Object[])oEnqNumber;
		Integer id = (Integer)oRiga[0];
		idEnqNumber.setValue(id);

		finestraDettaglio2.setVisible(true);
		viewDettaglio2(id);
	}
	
	
	public void onOK$bbEnqNumber2(Event event){
		changeORokEnqNumber2(event);
	}
	
	public void onChange$bbEnqNumber2(Event event){
		changeORokEnqNumber2(event); 
	}
	
	private void changeORokEnqNumber2(Event event){
		
		if (bbEnqNumber2.getValue()==null){
			return;
		}
		
		List lista = new ReqshipfuelassController().getListaEnqNumberQC_SC_CC_HI();
		
		boolean valido = false;
		for (Object object : lista) {
			Object[] oRiga = (Object[])object;
			Integer id = (Integer)oRiga[0];
			if ( Integer.valueOf( bbEnqNumber2.getValue() ).compareTo(id)==0){
				idEnqNumber.setValue(id);
				valido = true;
				break;
			}
		}

		if (!valido){
			Messagebox.show("Enquire number not valid! - "+bbEnqNumber2.getValue(), "Information", Messagebox.OK, Messagebox.INFORMATION);
			bbEnqNumber2.setValue(null);
			finestraDettaglio2.setVisible(false);
			tbAgentID.setValue("");
			tbAgentName.setValue("");
			tbCountry.setValue("");
			tbBoatName.setValue("");
			tbBoatContact.setValue("");
			dbDeliveryDate.setValue(null);
			dbDeliveryDate.setButtonVisible(false);
			tbPortToRefuel.setValue("");			
			tbCountry.setValue("");
			tbArt15.setValue( "NO" );
			
		} else {
			finestraDettaglio2.setVisible(true);
			idEnqNumber.setValue(Integer.valueOf( bbEnqNumber2.getValue() ));
			viewDettaglio2(Integer.valueOf( bbEnqNumber2.getValue() ));
		}
	}
		
	private void viewDettaglio2(Integer idEnqNumber){
		ListModelList listModelListEnqNumber = new ListModelList();
		listModelListEnqNumber.addAll(new ReqshipfuelassdetailController().getListQC_SC_CC_HI(idEnqNumber));		
		boxDetail.setModel(listModelListEnqNumber);
		boxDetail.setItemRenderer(new EnqNumberDetail2Renderer());
		
		// per visualizzare il combobox del supplier
		List<Supplier> listSupplier = new ArrayList<Supplier>();
		List<Reqshipfuelassdetail> detailReqShipFuelass = new ReqshipfuelassdetailController().getListQC_SC_CC_HI(idEnqNumber);
		for (Reqshipfuelassdetail reqshipfuelassdetail : detailReqShipFuelass) {
			Integer id = reqshipfuelassdetail.getSupplierid();
			if (id!=null && !id.equals(0)){
				boolean trovato = false;
				for (Supplier supplier : listSupplier) {
					if (supplier.getSupplid().equals(id)){
						trovato = true;
						break;
					}
				}
				if (!trovato){
					Supplier supplier = new SupplierController().getxId(id);							
					listSupplier.add(supplier);
				}
			}
		}
		ListModelList listModelListSupplier = new ListModelList();
		listModelListSupplier.addAll(listSupplier);		
		cbSupplierSelected.setModel(listModelListSupplier);
		cbSupplierSelected.setItemRenderer(new SupplierSelectedItemRenderer());
		
		Component tmp = finestraDettaglio2.getFellow("tbHowManyRecords");
		tbHowManyRecords = (Textbox) tmp; 
		tbHowManyRecords.setValue("Contains "+listModelListEnqNumber.getSize()+" record/s");
		// aggiorno dati agent id se c'è
		
		tbAgentID.setValue("");
		tbAgentName.setValue("");
		tbCountry.setValue("");
		
		
		
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idEnqNumber);
		if (reqshipfuelass.getAgentid()!=null && reqshipfuelass.getAgentid().compareTo(0)!=0){
			tbAgentID.setValue(""+reqshipfuelass.getAgentid());
			tbAgentName.setValue(reqshipfuelass.getAgent());
		}
		
		tbBoatName.setValue(reqshipfuelass.getVesselname());
		tbBoatContact.setValue(reqshipfuelass.getCaptain());
		dbDeliveryDate.setValue(reqshipfuelass.getDeliverydt());
		dbDeliveryDate.setButtonVisible(false);
		tbPortToRefuel.setValue(reqshipfuelass.getPorttoref());
		
		if (reqshipfuelass.getIdportref()!=null && reqshipfuelass.getIdportref()!=0){
			Port porto = new PortController().getPortxId(reqshipfuelass.getIdportref());
			tbCountry.setValue(porto.getCountry());
		}
				
		tbArt15.setValue( (reqshipfuelass.getArt15()==null||!reqshipfuelass.getArt15()?"NO":"SI") );
		
	}
	
	
	
	private class EnqNumberDetail2Renderer implements ListitemRenderer {
		
		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Reqshipfuelassdetail reqshipfuelassdetail = (Reqshipfuelassdetail)data;

			Textbox tbIdEnq = new Textbox(""+reqshipfuelassdetail.getId());
			tbIdEnq.setWidth("50px");
			tbIdEnq.setReadonly(true);

			//+ " of "+ General.paddingString(""+boxDetail.getModel().getSize(), 2, '0', true )
			Textbox tbRowNumber = new Textbox("" + General.paddingString(""+reqshipfuelassdetail.getSeq(), 2, '0', true) );
			tbRowNumber.setWidth("30px");
			tbRowNumber.setReadonly(true);
					
			Textbox tbProductName = new Textbox(reqshipfuelassdetail.getProductname());
			tbProductName.setCols(25);
			//tbProductName.setRows(2);
			tbProductName.setReadonly(true);
			
			Textbox tbProductId = new Textbox(""+reqshipfuelassdetail.getProductid());
			tbProductId.setWidth("60px");
			tbProductId.setReadonly(true);
			
			Textbox tbQuantity = new Textbox( General.decimalFormat("#,##0.000", reqshipfuelassdetail.getQuantity()) );
			tbQuantity.setWidth("80px");
			tbQuantity.setStyle("text-align: right;");
			tbQuantity.setReadonly(true);
			
			Textbox tbUM = new Textbox(""+reqshipfuelassdetail.getUm());
			tbUM.setWidth("40px");
			tbUM.setReadonly(true);

			Textbox tbCodStatus = new Textbox(""+reqshipfuelassdetail.getStat());
			tbCodStatus.setWidth("40px");
			tbCodStatus.setReadonly(true);

			Textbox tbDesStatus = new Textbox(""+new StatusController().getXCodice(reqshipfuelassdetail.getStat(), false).getDescription() );
			tbDesStatus.setWidth("200px");
			tbDesStatus.setReadonly(true);

			final Integer idMasterDetail = reqshipfuelassdetail.getIdmaster();

			Label lblSupplier = new Label("Supplier: ");
			lblSupplier.setStyle("color:blue");
			String supplierName = "";
			if (reqshipfuelassdetail.getSupplierid()!=null){
				Supplier supplier = new SupplierController().getxId(reqshipfuelassdetail.getSupplierid());
				
				if (supplier!=null){
					supplierName = supplier.getCompanyname();
				}
			}
			Textbox tbSupplier = new Textbox(supplierName);
			tbSupplier.setWidth("240px");
			tbSupplier.setReadonly(true);
			
						
			Combobox cbSupplier = new Combobox();
			cbSupplier.setWidth("50px");
			//cbSupplier.setReadonly(true);
			cbSupplier.setDisabled(true);
			List<Reqquote> reqquoteList = new ReqquoteController().getListxIdReqEreqseq(reqshipfuelassdetail.getId(), reqshipfuelassdetail.getSeq());
			Integer iSelected = 0;
			for (int i = 0; i < reqquoteList.size(); i++) {
				Reqquote reqquote = reqquoteList.get(i);
				if (reqquote.getSuppid()!=null && reqquote.getSuppid()!=0 && reqshipfuelassdetail.getSupplierid()!=null && reqshipfuelassdetail.getSupplierid() != 0 && reqquote.getSuppid().intValue() == reqshipfuelassdetail.getSupplierid() ){
					iSelected = i;
				}				
			}

			
			ListModelList listModelList = new ListModelList();
			listModelList.addAll(reqquoteList);
			
			if (reqquoteList.size()>0){
				listModelList.addToSelection(listModelList.get(iSelected));
			}
			
			cbSupplier.setModel(listModelList);
			cbSupplier.setItemRenderer(new SupplierItemRenderer());

			cbSupplier.addEventListener("onSelect", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
				
					List<Component> listaChilds = event.getTarget().getParent().getChildren();
					Textbox tbDescSupplier = (Textbox)event.getTarget().getParent().getLastChild();
					Textbox tbIdSupplier = (Textbox)listaChilds.get(0);
					Combobox co = (Combobox) componente;
					tbDescSupplier.setValue(co.getSelectedItem().getDescription());
					tbIdSupplier.setValue(co.getSelectedItem().getLabel());
					
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					reqdet.setSupplierid( Integer.valueOf( co.getSelectedItem().getLabel()) );
					new ReqshipfuelassdetailController().update(reqdet);	
				}
				});			

			
			Textbox tbIdSupplier = new Textbox(""+(reqshipfuelassdetail.getSupplierid()==null?"":reqshipfuelassdetail.getSupplierid()));
			tbIdSupplier.setWidth("40px");
			tbIdSupplier.setReadonly(true);
			tbIdSupplier.setVisible(false);
			
			
			// Purchase
			Textbox tbSuppCurrency = new Textbox(""+reqshipfuelassdetail.getSuppcurr());
			tbSuppCurrency.setWidth("30px");
			tbSuppCurrency.setReadonly(true);

			Textbox tbSuppUM =  new Textbox(""+reqshipfuelassdetail.getSuppumquote());
			tbSuppUM.setWidth("30px");
			tbSuppUM.setReadonly(true);
			
			Textbox tbSuppUnitPrice =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getSuppnetunitcost() ) );
			tbSuppUnitPrice.setWidth("80px");
			tbSuppUnitPrice.setReadonly(true);
			tbSuppUnitPrice.setStyle("text-align: right;");

			Textbox tbSuppNetTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getSuppnetcost() ) );
			tbSuppNetTotal.setWidth("80px");
			tbSuppNetTotal.setReadonly(true);
			tbSuppNetTotal.setStyle("text-align: right;");

			Textbox tbSuppQtyQuote =  new Textbox(""+General.decimalFormat("#,##0.000", reqshipfuelassdetail.getSuppqtyquote() ) );
			tbSuppQtyQuote.setWidth("70px");
			tbSuppQtyQuote.setReadonly(true);
			tbSuppQtyQuote.setStyle("text-align: right;");

			Label lblSuppVAT = new Label("VAT %");
			lblSuppVAT.setStyle("color:black");
			
			Textbox tbSuppVat =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getSuppvat() ) );
			tbSuppVat.setWidth("80px");
			tbSuppVat.setReadonly(true);
			tbSuppVat.setStyle("text-align: right;");

			
			Textbox tbSuppQuoteDt =  new Textbox(""+General.formatoFechaOra( reqshipfuelassdetail.getQuotedt() ) );
			tbSuppQuoteDt.setWidth("120px");
			tbSuppQuoteDt.setReadonly(true);
			
			Datebox tbSuppConfirmDt =  new Datebox();
			tbSuppConfirmDt.setValue(reqshipfuelassdetail.getConfirmdt());
			//tbSuppConfirmDt.setWidth("120px");
			tbSuppConfirmDt.setFormat("dd/MM/yyyy");
			
			tbSuppConfirmDt.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					try {
						Datebox textboxDM = (Datebox) componente;
						Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
						reqdet.setConfirmdt( General.date2SqlTimestamp( textboxDM.getValue() ) );
						reqdet.setConfirmcustdt(reqdet.getConfirmdt());
						new ReqshipfuelassdetailController().update(reqdet);
						
						Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent().getParent().getParent()).getIndex();
						Object oDetail = boxDetail.getItemAtIndex(iIndex).getAttribute("rigaEnqDetailNumber");						
						Reqshipfuelassdetail reqdet2 = (Reqshipfuelassdetail)oDetail;
						reqdet2.setConfirmdt(General.date2SqlTimestamp( reqdet.getConfirmdt() ));
						reqdet2.setConfirmcustdt(reqdet.getConfirmdt());
						
						ListModelList lml = (ListModelList) boxDetail.getListModel();

						if (lml.indexOf(reqdet2) != -1) {
							lml.set(lml.indexOf(reqdet2), reqdet2);
						}

						
						
						General.showNotify("Confirm Date updated..", null, 2000); 
					} catch (Exception e) {
						General.showNotify("Error updating Confirm Date..", null, 4000);
					}

				}
				});
			

			
			Button btnSupplier = new Button();
			btnSupplier.setLabel("Supplier");
			
			btnSupplier.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					
					Sessions.getCurrent().setAttribute("idSelected", iIndex);
					
					editQ2CSuppSect(idMasterDetail);
					
				}
					
			});

			
			Label lblSuppTotal = new Label("TOTAL");
			lblSuppTotal.setStyle("color:black");

			Textbox tbSuppTotalCost =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getSupptotalcost() ) );
			tbSuppTotalCost.setWidth("80px");
			tbSuppTotalCost.setReadonly(true);
			tbSuppTotalCost.setStyle("text-align: right;");


			
			// Confirm Customer
			
			Textbox tbCustCurrency = new Textbox(""+reqshipfuelassdetail.getCurr());
			tbCustCurrency.setWidth("30px");
			tbCustCurrency.setReadonly(true);

			Textbox tbCustUM =  new Textbox(""+reqshipfuelassdetail.getCustum());
			tbCustUM.setWidth("30px");
			tbCustUM.setReadonly(true);
			
			Textbox tbCustNetUnitCost =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getCustnetunitcost() ) );
			tbCustNetUnitCost.setWidth("70px");
			tbCustNetUnitCost.setReadonly(true);
			tbCustNetUnitCost.setStyle("text-align: right;");

			Textbox tbCustNetTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getCustnetcost() ) );
			tbCustNetTotal.setWidth("80px");
			tbCustNetTotal.setReadonly(true);
			tbCustNetTotal.setStyle("text-align: right;");

			Textbox tbCustEarnPerc =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getEarn() ) + " %" );
			tbCustEarnPerc.setWidth("50px");
			tbCustEarnPerc.setReadonly(true);
			tbCustEarnPerc.setStyle("text-align: right;");	
			
			Label lblCustExChRate = new Label("ExChRate");
			lblCustExChRate.setStyle("color:black");

			
			
			Textbox tbCustQty =  new Textbox(""+General.decimalFormat("#,##0.000", reqshipfuelassdetail.getCustqtyquote() ) );
			tbCustQty.setWidth("60px");
			tbCustQty.setReadonly(true);
			tbCustQty.setStyle("text-align: right;");

			Label lblCustVAT = new Label("VAT");
			lblCustVAT.setStyle("color:black");
			
			Textbox tbCustVat =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getCustvat() ) );
			tbCustVat.setWidth("60px");
			tbCustVat.setReadonly(true);
			tbCustVat.setStyle("text-align: right;");

			Textbox tbCustEartTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getTotearn() ) );
			tbCustEartTotal.setWidth("60px");
			tbCustEartTotal.setReadonly(true);
			tbCustEartTotal.setStyle("text-align: right;");

			Textbox tbCustExChRate =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getExchrate()) );
			tbCustExChRate.setWidth("60px");
			tbCustExChRate.setReadonly(true);
			tbCustExChRate.setStyle("text-align: right; color: red;");

			
			Button btnCustomer = new Button();
			btnCustomer.setLabel("Customer");
			
			btnCustomer.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
					boxEnqNumber.setSelectedIndex(iIndex);
					
					Sessions.getCurrent().setAttribute("idSelected", iIndex);
					
					editQ2CCustSect(idMasterDetail);
					
				}
					
			});
			
			
			
			Label lblCustTotal = new Label("TOTAL");
			lblCustTotal.setStyle("color:black");

			Textbox tbCustTotal =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getCusttotsalevat() ) );
			tbCustTotal.setWidth("80px"); 
			tbCustTotal.setReadonly(true);
			tbCustTotal.setStyle("text-align: right;");
			
			Label lblCustStatus = new Label("Status");
			lblCustStatus.setStyle("color:black");
			
			Textbox tbCustStatus =  new Textbox(""+reqshipfuelassdetail.getStat());
			tbCustStatus.setWidth("40px"); 
			tbCustStatus.setReadonly(true);
			tbCustStatus.setStyle("text-align: center; color:red;");

			Label lblCustCustInvoice = new Label("CustInvoice");
			lblCustCustInvoice.setStyle("color:black");
			
			
			Separator separator = new Separator();
			separator.setWidth("20px");			
			
			Hbox hbox00 = new Hbox();
			Hbox hbox01 = new Hbox();
			Hbox hboxa1 = new Hbox();
			Hbox hboxa2 = new Hbox();
			Hbox hboxa3 = new Hbox();
			Hbox hboxa4 = new Hbox();
			Hbox hboxa5 = new Hbox();
			Hbox hboxa6 = new Hbox();
			Hbox hboxa7 = new Hbox();
			Hbox hboxa8 = new Hbox();
			Hbox hboxa9 = new Hbox();
			
			Hbox hboxb1 = new Hbox();
			Hbox hboxb2 = new Hbox();
			Hbox hboxb3 = new Hbox();
			Hbox hboxb4 = new Hbox();
			Hbox hboxc1 = new Hbox();
			Hbox hboxc2 = new Hbox();
			Hbox hboxc3 = new Hbox();
			Hbox hboxc4 = new Hbox();
			//
			Vbox vbox1 = new Vbox();
			Vbox vbox2 = new Vbox();
			Vbox vbox3 = new Vbox();
			Hbox hboxc5 = new Hbox();
			Hbox hboxc6 = new Hbox();
			
			Groupbox gbox1 = new Groupbox();
			//Groupbox gbox2 = new Groupbox();
			Groupbox gbox3 = new Groupbox();
			Groupbox gbox3b = new Groupbox();
			//gbox3b.setStyle("border-color: red;");
			gbox3b.setContentStyle("border: 2px solid red; padding 3px");
			
			hboxa2.setPack("end");
			hboxa2.setAlign("end");
			
			
			// SUPPLIER
			
			hboxa1.appendChild(tbIdEnq);
			hboxa1.appendChild(tbRowNumber);	
			hboxa1.appendChild(tbProductName);
			//hboxa1.appendChild(lblQuoteDt);
			hboxa1.appendChild(tbSuppQuoteDt);
			hboxa1.appendChild(tbSuppConfirmDt);
			hboxa1.appendChild(tbSuppCurrency);
			
			hboxa2.appendChild( new Label( reqshipfuelassdetail.getPartno() ));

			hboxa3.appendChild(lblSupplier);
			hboxa3.appendChild(tbIdSupplier);
			hboxa3.appendChild(cbSupplier);
			hboxa3.appendChild(tbSupplier);
			separator = new Separator();
			separator.setWidth("100px");
			hboxa3.appendChild( separator );
			
			Textbox tbSuppVatPerc =  new Textbox(""+General.decimalFormat("#,##0.00", reqshipfuelassdetail.getSuppvatperc() ) );
			tbSuppVatPerc.setWidth("60px");
			tbSuppVatPerc.setReadonly(true);
			tbSuppVatPerc.setStyle("text-align: right;");
			hboxa3.appendChild(lblSuppVAT);			
			hboxa3.appendChild(tbSuppVatPerc); 

			
			// Net
			hboxa4.appendChild(tbSuppUnitPrice);
			
			Label tmpLabel = new Label("Net");
			tmpLabel.setWidth("60px");
			hboxa4.appendChild(tmpLabel);
			hboxa4.appendChild(tbSuppNetTotal);

			
			Textbox tbSuppUnitVat =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getSuppunitvat() ) );
			tbSuppUnitVat.setWidth("80px");
			tbSuppUnitVat.setReadonly(true);
			tbSuppUnitVat.setStyle("text-align: right;");
			
			hboxa5.appendChild(tbSuppUnitVat);
			Label tmpLabel2 = new Label("VAT");
			tmpLabel2.setWidth("60px");
			hboxa5.appendChild(tmpLabel2);
			hboxa5.appendChild(tbSuppVat);
			
			Textbox tbSuppUnitCostDisc =  new Textbox(""+General.decimalFormat("#,##0.0000", reqshipfuelassdetail.getSuppunitcostdisc() ) );
			tbSuppUnitCostDisc.setWidth("80px");
			tbSuppUnitCostDisc.setReadonly(true);
			tbSuppUnitCostDisc.setStyle("text-align: right;");
			
			hboxa6.appendChild(tbSuppUnitCostDisc);
			Label tmpLabel3 = new Label("Total");
			tmpLabel3.setWidth("60px");
			hboxa6.appendChild(tmpLabel3);
			hboxa6.appendChild(tbSuppTotalCost);
			
			hboxa7.appendChild(new Label("Phys/Trader"));
			
			
			Combobox cbPhysical = new Combobox();
			cbPhysical.setWidth("250px");

			List physicalList = new SupplierController().getListPhysical(null);
			listModelList = new ListModelList();
			List<Supplier> suppVuoto = new ArrayList<Supplier>();
			Supplier suppZero = new Supplier();
			suppZero.setCompanyname("");
			//suppZero.setSupplid(0);
			suppVuoto.add(suppZero);
			listModelList.addAll(suppVuoto);
			listModelList.addAll(physicalList);
			
			if (reqshipfuelassdetail.getPhistraderId() != null
					&& reqshipfuelassdetail.getPhistraderId() != 0) {
				for (int i = 0; i < physicalList.size(); i++) {
					Supplier suppPhysical = (Supplier) physicalList.get(i);
					if (suppPhysical.getSupplid().equals( reqshipfuelassdetail.getPhistraderId() ) ) {
						//cbPhysical.setSelectedIndex(i);
						listModelList.addToSelection(listModelList.get(i+1));
						break;
					}
				}
			}

			// per i combobox prima devo aggiungere la seleziona al model list, e poi aggiungere il modello
			cbPhysical.setModel(listModelList);
			cbPhysical.setItemRenderer(new PhysicalItemRenderer());
			cbPhysical.setReadonly(true);


			cbPhysical.addEventListener("onSelect", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
				
					Combobox co = (Combobox) componente;
					String testoId = co.getSelectedItem().getLabel();
					String testoNome = "";
					
					if (!testoId.isEmpty()){
						testoNome = testoId.substring(testoId.indexOf(" ")+3);
						testoId = testoId.substring( 0, testoId.indexOf(" "));
					} else {
						testoId = "0";
					}
					//System.out.println(testoNome);
					
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					reqdet.setPhistraderId(Integer.valueOf( testoId ));
					reqdet.setPhistraderName(testoNome);
					new ReqshipfuelassdetailController().update(reqdet);
					General.showNotify("Phys/Trader updated..", null, 2000);					
				}
				});			
			
			
			
			hboxa7.appendChild(cbPhysical);
			hboxa7.appendChild(new Label("QtyQuote"));
			hboxa7.appendChild(tbSuppQtyQuote);
			hboxa7.appendChild(tbSuppUM);
			//
			
			
			Label lblNote = new Label("Note");
			lblNote.setStyle("color:blue");
			
			String note = reqshipfuelassdetail.getNote();
			note = (note==null?"":note);
			Textbox tbRigaNota = new Textbox(""+note);
			//tbRigaNota.setWidth("200px");
			//tbRigaNota.setReadonly(true);
			tbRigaNota.setRows(2);
			tbRigaNota.setCols(50);
			
			tbRigaNota.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					Textbox textboxNota = (Textbox) componente;					
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					reqdet.setNote(textboxNota.getValue());
					new ReqshipfuelassdetailController().update(reqdet);	
					General.showNotify("Note updated..", null, 2000); 
				}
				});			
			
			hboxa8.appendChild(lblNote);			
			hboxa8.appendChild(tbRigaNota);
			
			
			Label lblSuppDelMethod = new Label("DeliveryMethod");
			lblSuppDelMethod.setStyle("color:black");

			Textbox tbSuppDelMethod =  new Textbox(""+reqshipfuelassdetail.getDeliverymethod() );
			if (reqshipfuelassdetail.getDeliverymethod()==null){
				tbSuppDelMethod.setValue("");
			}
			tbSuppDelMethod.setWidth("250px");
			tbSuppDelMethod.setMaxlength(15);
			tbSuppDelMethod.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					Textbox textboxDM = (Textbox) componente;					
					Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
					reqdet.setDeliverymethod(textboxDM.getValue());
					new ReqshipfuelassdetailController().update(reqdet);	
					General.showNotify("Delivery Method updated..", null, 2000);
				}
				});			

			
			hboxa8.appendChild(lblSuppDelMethod);			
			hboxa8.appendChild(tbSuppDelMethod);
			
			
			// CUSTOMER
			hboxc1.appendChild(tbCustNetUnitCost);
			hboxc1.appendChild(tbCustCurrency);
			separator = new Separator();
			separator.setWidth("10px");
			hboxc1.appendChild(separator);
			hboxc1.appendChild(tbCustUM);
			separator = new Separator();
			separator.setWidth("15px");
			hboxc1.appendChild(separator);
			hboxc1.appendChild(new Label("Net:"));
			hboxc1.appendChild(tbCustNetTotal);
			//hboxc1.appendChild(lblCustStatus);
			hboxc1.appendChild(tbCustStatus);

			//hboxc1.appendChild(tbCustEarnPerc);
			//hboxc1.appendChild(lblCustExChRate);
			
			
			Textbox tbCustUnitVat = new Textbox();
			tbCustUnitVat.setValue( General.decimalFormat("###,##0.0000", reqshipfuelassdetail.getCustunitvat()));
			tbCustUnitVat.setReadonly(true);
			tbCustUnitVat.setWidth("80px");
			tbCustUnitVat.setStyle("text-align: right;");
			
			hboxc2.appendChild(tbCustUnitVat); 
			//hboxc2.appendChild(tbCustQty);
			separator = new Separator();
			separator.setWidth("100px");
			hboxc2.appendChild(separator);
			hboxc2.appendChild(lblCustVAT);
			separator = new Separator();
			separator.setWidth("2px");
			hboxc2.appendChild(separator);
			
			Textbox tbCustTotalVat = new Textbox();
			tbCustTotalVat.setValue( General.decimalFormat("###,##0.00", reqshipfuelassdetail.getCustvat()));
			tbCustTotalVat.setReadonly(true);
			tbCustTotalVat.setWidth("80px");
			tbCustTotalVat.setStyle("text-align: right;");
			hboxc2.appendChild(tbCustTotalVat);

			
			Textbox tbCustUnitTotal = new Textbox();
			Double custUnitTotal = reqshipfuelassdetail.getCustnetunitcost()+reqshipfuelassdetail.getCustunitvat();
			tbCustUnitTotal.setValue( General.decimalFormat("###,##0.0000", custUnitTotal));
			tbCustUnitTotal.setReadonly(true);
			tbCustUnitTotal.setWidth("80px");
			tbCustUnitTotal.setStyle("text-align: right;");
			hboxc3.appendChild(tbCustUnitTotal);
			separator = new Separator();
			separator.setWidth("5px");
			hboxc3.appendChild(separator);
			
			Label lblCustVatPerc = new Label("VAT %");
			hboxc3.appendChild(lblCustVatPerc);
			Textbox tbCustVatPerc = new Textbox();
			tbCustVatPerc.setValue( General.decimalFormat("##0.00", reqshipfuelassdetail.getCustvatperc()));
			tbCustVatPerc.setReadonly(true);
			tbCustVatPerc.setWidth("40px");
			tbCustVatPerc.setStyle("text-align: right;");
			hboxc3.appendChild(tbCustVatPerc);
			
			Label lblCustTotSale = new Label("TOTAL");
			hboxc3.appendChild(lblCustTotSale);
			Textbox tbCustTotSaleVat = new Textbox();
			tbCustTotSaleVat.setValue( General.decimalFormat("###,##0.00", reqshipfuelassdetail.getCusttotsalevat()));
			tbCustTotSaleVat.setReadonly(true);
			tbCustTotSaleVat.setWidth("80px");
			tbCustTotSaleVat.setStyle("text-align: right;");
			hboxc3.appendChild(tbCustTotSaleVat);			
			

			Label lblCustQtyQuote = new Label("QtyQuote: ");
			hboxc4.appendChild(lblCustQtyQuote); 
			hboxc4.appendChild(tbCustQty);
			Label lblCustConfDt = new Label("ConfCustDt:");
			hboxc4.appendChild(lblCustConfDt);
			Datebox dbCustConfirmDt =  new Datebox();
			dbCustConfirmDt.setValue(reqshipfuelassdetail.getConfirmcustdt()); 
			dbCustConfirmDt.setFormat("dd/MM/yyyy HH:mm");
			dbCustConfirmDt.setWidth("120px");
			dbCustConfirmDt.setReadonly(false);
			dbCustConfirmDt.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					try {
						Datebox textboxDM = (Datebox) componente;
						Reqshipfuelassdetail reqdet = new ReqshipfuelassdetailController().getxId(idMasterDetail);
						reqdet.setConfirmcustdt( General.date2SqlTimestamp( textboxDM.getValue() ) );
						new ReqshipfuelassdetailController().update(reqdet);
						
						
						Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent().getParent()).getIndex();
						Object oDetail = boxDetail.getItemAtIndex(iIndex).getAttribute("rigaEnqDetailNumber");						
						Reqshipfuelassdetail reqdet2 = (Reqshipfuelassdetail)oDetail;
						reqdet2.setConfirmcustdt(General.date2SqlTimestamp( textboxDM.getValue() ));
						
						ListModelList lml = (ListModelList) boxDetail.getListModel();

						if (lml.indexOf(reqdet2) != -1) {
							lml.set(lml.indexOf(reqdet2), reqdet2);
						}

						
						General.showNotify("Confirm Customer Date updated..", null, 2000);
					} catch (Exception e) {
						General.showNotify("Error updating Confirm Customer Date..", null, 4000);
					}

				}
				});
			
			hboxc4.appendChild(dbCustConfirmDt);

			
			
			Textbox tbCustCustInvoice =  new Textbox(""+reqshipfuelassdetail.getCustinvoicenumber());
			tbCustCustInvoice.setWidth("40px"); 
			tbCustCustInvoice.setReadonly(true);
			tbCustCustInvoice.setStyle("text-align: left;");
			
			Textbox tbCustCustInvoiceStatus =  new Textbox("");
			tbCustCustInvoiceStatus.setWidth("40px"); 
			tbCustCustInvoiceStatus.setReadonly(true);
			tbCustCustInvoiceStatus.setStyle("text-align: left;");
			
			Custinvoicedetail custinvoicedetail = new CustinvoicedetailController().getCustinvoicedetail(reqshipfuelassdetail.getProductname(), reqshipfuelassdetail.getId());
			if (custinvoicedetail!=null){
				tbCustCustInvoice.setValue(""+custinvoicedetail.getCustnuminvoice());
				tbCustCustInvoiceStatus.setValue(custinvoicedetail.getStat());
			}

			Label lblCustSuppInvoice = new Label("SuppInvoice");
			lblCustSuppInvoice.setStyle("color:black");
			
			String custSuppInvoice = reqshipfuelassdetail.getSuppinvoicenumber();
			custSuppInvoice = (custSuppInvoice==null?"":custSuppInvoice);
			Textbox tbCustSuppInvoice =  new Textbox(""+custSuppInvoice);
			tbCustSuppInvoice.setWidth("40px"); 
			tbCustSuppInvoice.setReadonly(true);
			tbCustSuppInvoice.setStyle("text-align: left;");
			
			Textbox tbCustSuppInvoiceStatus =  new Textbox("");
			tbCustSuppInvoiceStatus.setWidth("40px"); 
			tbCustSuppInvoiceStatus.setReadonly(true);
			tbCustSuppInvoiceStatus.setStyle("text-align: left;");
			
			Suppinvoicedetail suppinvoicedetail = new SuppinvoicedetailController().getSuppinvoicedetail(reqshipfuelassdetail.getProductname(), reqshipfuelassdetail.getId());
			if (suppinvoicedetail!=null){
				tbCustSuppInvoice.setValue(""+suppinvoicedetail.getSuppnuminvoice());
				tbCustSuppInvoiceStatus.setValue(suppinvoicedetail.getStat());
			}
			
			hboxc5.appendChild(lblCustCustInvoice);
			hboxc5.appendChild(tbCustCustInvoice);
			hboxc5.appendChild(tbCustCustInvoiceStatus);
			
			hboxc6.appendChild(lblCustSuppInvoice);
			hboxc6.appendChild(tbCustSuppInvoice);
			hboxc6.appendChild(tbCustSuppInvoiceStatus);
			
			
			vbox3.appendChild(hboxc5);
			vbox3.appendChild(hboxc6);
			gbox3b.appendChild(vbox3);
			
			//hboxc4.appendChild(gbox3b);
			
			vbox1.appendChild(hboxa1);
			vbox1.appendChild(hboxa2);
			vbox1.appendChild(hboxa3);
			vbox2.appendChild(hboxa4);
			vbox2.appendChild(hboxa5);
			vbox2.appendChild(hboxa6);
			hbox01.appendChild(vbox1);
			hbox01.appendChild(vbox2);
			
			gbox1.appendChild(hbox01);
			gbox1.appendChild(hboxa7);
			gbox1.appendChild(hboxa8);
			//
			gbox3.appendChild(hboxc1);
			gbox3.appendChild(hboxc2);
			gbox3.appendChild(hboxc3);
			gbox3.appendChild(hboxc4);
			gbox3.appendChild(gbox3b); 
			
			hbox00.appendChild(gbox1);
			//hbox00.appendChild(gbox2);
			hbox00.appendChild(gbox3);
			
			gbox1.setHeight("152px");
			
			Listcell listcell = new Listcell();
			
			listcell.appendChild(hbox00);
			
			listcell.setParent(item);
			
			item.setAttribute("rigaEnqDetailNumber", data);

		}
	}
	
	
	private class PhysicalItemRenderer implements ComboitemRenderer {
		
		@Override
		public void render(Comboitem item, Object data, int index)
				throws Exception {
			
			Supplier su = (Supplier)data;
			if (su.getSupplid()==null){
				item.setLabel("");
				item.setDescription("");
			} else {
				item.setLabel(""+su.getSupplid() + " - " + su.getCompanyname());
				item.setDescription("P: "+( su.getPhysical()==null || !su.getPhysical() ? "NO" : "SI" ) + " T: "+( su.getTrader()==null || !su.getTrader() ? "NO" : "SI") );
			}
		}


	}
	
	
	private class SupplierSelectedItemRenderer implements ComboitemRenderer {
		
		@Override
		public void render(Comboitem item, Object data, int index)
				throws Exception {
			
			Supplier su = (Supplier)data;
			item.setDescription(""+su.getSupplid());
			item.setLabel(su.getCompanyname());			
		}


	}

	public void onClick$btnPrintConfirmationSupplier(){
		Integer orderNumber = 0;
		Integer idSupplierSelected = 0;
		
		if ( bbEnqNumber != null ){
			if ( bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty()){
				return;
			}
			orderNumber = Integer.valueOf( bbEnqNumber.getValue() );
		} else if ( bbEnqNumber2 != null ) {
			if ( bbEnqNumber2.getValue()==null || bbEnqNumber2.getValue().isEmpty()){
				return;
			}			
			orderNumber = Integer.valueOf( bbEnqNumber2.getValue() );
		} else {
			return;
		}
		
		if (cbSupplierSelected.getSelectedIndex()==-1){
			//Select at least a supplier!
			General.showNotify("Select at least a supplier!", null, 4000);
			return;
		}
		
		idSupplierSelected = Integer.valueOf( cbSupplierSelected.getSelectedItem().getDescription() );
		
		if (Messagebox.show("Operation can't be cancelled, press Yes to continue?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			return;
		}
		
		Reqshipfuelass rsfa = new ReqshipfuelassController().getxId(orderNumber);
		
		/*
		for (int i = 0; i < boxDetail.getListModel().getSize(); i++) {
			Object oDetail = boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
			
			Reqshipfuelassdetail reqdet = (Reqshipfuelassdetail)oDetail;
			if (reqdet.getStat().equalsIgnoreCase("QC") && reqdet.getConfirmdt() != null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) ){
				reqdet.setStat("SC"); // from QC (quoted to customer) To SC (supplier confirmed)
				new ReqshipfuelassdetailController().update(reqdet);
			}
			if (reqdet.getConfirmdt()==null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) ){
				new General().MsgBox("No confirm date is signed on record # " + reqdet.getSeq() + ", print cancelled", "NFYS");
			} else if (reqdet.getConfirmdt()==null && ( reqdet.getRefused()!=null && reqdet.getRefused()==true ) ){
				new General().MsgBox("Request(s) cancelled ", "NFYS");
			}
			boxDetail.invalidate(); // to refresh listbox
		}
		*/

		if (Messagebox.show("Do you want to print Supplier confirmation ?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) == Messagebox.YES){
			
			
			for (int i = 0; i < boxDetail.getListModel().getSize(); i++) {
				Object oDetail = boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
				Reqshipfuelassdetail reqdet = (Reqshipfuelassdetail)oDetail;
				
				if (reqdet.getConfirmdt()==null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) ){
					new General().MsgBox("No confirm date is signed on record # " + reqdet.getSeq() + ", print cancelled", "NFYS");
				} else if (reqdet.getConfirmdt()==null && ( reqdet.getRefused()!=null && reqdet.getRefused()==true ) ){
					new General().MsgBox("Request(s) cancelled ", "NFYS");
				} else if (reqdet.getStat().equalsIgnoreCase("QC") && reqdet.getConfirmdt() != null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) && reqdet.getSupplierid().equals(idSupplierSelected) ){
					reqdet.setStat("SC"); // from QC (quoted to customer) To SC (supplier confirmed)
					new ReqshipfuelassdetailController().update(reqdet);
				
					Supplier supp = new SupplierController().getxId(reqdet.getSupplierid());
					
					Suppinvoice[] suppInvoices = new SuppinvoiceController().get(orderNumber, idSupplierSelected);
					String tmpStatus = "SC";
					Integer recNumForDetail = null;
					if (suppInvoices.length>0){
						tmpStatus = suppInvoices[0].getStat();
						recNumForDetail = suppInvoices[0].getRecnum();
					}
					
					
					// hipotetical invoice, master record
					if (tmpStatus.equalsIgnoreCase("SC")){
						Suppinvoice suppInv = new Suppinvoice();
						suppInv.setOrder(reqdet.getId()); // id order
						suppInv.setSuppid(reqdet.getSupplierid()); // id supplier della riga					
						suppInv.setSuppname(supp.getCompanyname());
						suppInv.setCustname(rsfa.getVesselname());
						suppInv.setCustid(rsfa.getVesselnameid());
						suppInv.setPorttoref(rsfa.getPorttoref());
						suppInv.setPortidpass(rsfa.getIdportref());
						suppInv.setCreditterms(supp.getPaymentterms());
						suppInv.setCurr(reqdet.getSuppcurr());
						suppInv.setDeliverydt(rsfa.getDeliverydt());
						suppInv.setExchangerate(rsfa.getExchrate());
						suppInv.setStat("HI");
						suppInv.setType("A");
						suppInv.setArt15(rsfa.getArt15());
						suppInv.setInvoicedtreg( General.date2SqlTimestamp( new java.util.Date() ) );
						
						if (!supp.getPaymentterms().equalsIgnoreCase("E.O.M.")){
							Timestamp tmpTimeStamp = new Timestamp( rsfa.getDeliverydt().getTime() );
							Calendar cal = Calendar.getInstance();
							cal.setTime(tmpTimeStamp);
							Payment payment = new PaymentsController().getPaymentxTerms(supp.getPaymentterms());
							if (payment==null){
								payment = new Payment();
							}
							if (payment.getId()!=null && payment.getId()==0){
								payment.setDd(0);
							}
							cal.add(Calendar.DAY_OF_WEEK, payment.getDd());
							tmpTimeStamp.setTime(cal.getTime().getTime());
							suppInv.setDuedate(tmpTimeStamp);
						} else {
							// E.O.M
							Timestamp tmpTimeStamp = rsfa.getDeliverydt();
							Calendar cal = Calendar.getInstance();
							cal.setTime(tmpTimeStamp);
							//cal.add(Calendar.DAY_OF_WEEK, payment.getDd());
							cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));						
							tmpTimeStamp.setTime(cal.getTime().getTime());
							suppInv.setDuedate(tmpTimeStamp);
						}
						
						
						suppInv = new SuppinvoiceController().add(suppInv);
						recNumForDetail = suppInv.getRecnum();
					}
									
					// hipotetical invoice detail record
					Suppinvoicedetail[] suppInvoiceDetails = new SuppinvoicedetailController().get(orderNumber, idSupplierSelected, reqdet.getSeq());
					
					Suppinvoicedetail suppinvoicedetail = new Suppinvoicedetail();
					
					if (suppInvoiceDetails.length>0){
						suppinvoicedetail = suppInvoiceDetails[0];
					}
					
					suppinvoicedetail.setOrder(orderNumber);
					suppinvoicedetail.setSuppid(reqdet.getSupplierid());
					suppinvoicedetail.setSeq(reqdet.getSeq());
					suppinvoicedetail.setProductname(reqdet.getProductname());
					suppinvoicedetail.setPartno(reqdet.getPartno());
					suppinvoicedetail.setProductid(reqdet.getProductid());
					suppinvoicedetail.setQuantity(reqdet.getSuppqtyquote());
					suppinvoicedetail.setUnitprice(reqdet.getSuppunitcostdisc());
					suppinvoicedetail.setTotalamount(reqdet.getSupptotalcost());
					suppinvoicedetail.setSuppname(supp.getCompanyname());
					suppinvoicedetail.setRecnum(recNumForDetail);
					suppinvoicedetail.setCurr(reqdet.getSuppcurr());
					suppinvoicedetail.setCustname(rsfa.getVesselname());
					suppinvoicedetail.setCustid(rsfa.getVesselnameid());
					suppinvoicedetail.setUm(reqdet.getSuppumquote());
					suppinvoicedetail.setStat("HI"); // invoice hipotetic status
					suppinvoicedetail.setSuppvat(reqdet.getSuppvat());
					suppinvoicedetail.setSupptaxed(reqdet.getSuppnetcost());
					suppinvoicedetail.setSuppvatperc(reqdet.getSuppvatperc());
					suppinvoicedetail.setType("A");
					
					if (suppInvoiceDetails.length>0){
						new SuppinvoicedetailController().update(suppinvoicedetail);
					} else {
						new SuppinvoicedetailController().add(suppinvoicedetail);
					}
					
				}
				
			}
			
			boxDetail.invalidate();
			
			try {
				printConfirmationToSupplier(orderNumber, idSupplierSelected);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (JRException e) {
				e.printStackTrace();
			}
			
		} else {
			new General().MsgBox("You will be able to obtain print confirmation later!", "NFYS");
		}
		
	}
	
	
	private void printConfirmationToSupplier(Integer numOrder, Integer idSupplierSelected) throws SQLException, JRException, FileNotFoundException {

		
		Sessions.getCurrent().setAttribute("richiestaData", null);
		
		Window finestraReqDate = (Window) Executions.createComponents(
				"/richiestaData.zul", null, null);
		finestraReqDate.doModal();
		
		Date data = (Date) Sessions.getCurrent().getAttribute("richiestaData");
		if (data==null){
			return;
		}
		
		Sessions.getCurrent().setAttribute("richiestaData", null);
		
		
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props);
		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		//params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );
		params.put( "PAR_REQUEST_ID", numOrder );
		params.put( "PAR_SUPPLIER_ID", idSupplierSelected );
		params.put("SUBREPORT_DIR", new General().percorsoFincati() + "/");
		params.put( "PAR_DATA", data);

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/ConfirmToSupplier.jasper";
		//System.out.println(fileJasper);
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/ConfirmToSupplier.pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");
	}
	
	
	
	public void onClick$btnPrintConfirmationCustomer(){
		Integer orderNumber = 0;
		//Integer idSupplierSelected = 0;
		Integer idCustomer = 0;
		
		if ( bbEnqNumber != null ){
			if ( bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty()){
				return;
			}
			orderNumber = Integer.valueOf( bbEnqNumber.getValue() );
		} else if ( bbEnqNumber2 != null ) {
			if ( bbEnqNumber2.getValue()==null || bbEnqNumber2.getValue().isEmpty()){
				return;
			}			
			orderNumber = Integer.valueOf( bbEnqNumber2.getValue() );
		} else {
			return;
		}
		
		//idSupplierSelected = Integer.valueOf( cbSupplierSelected.getSelectedItem().getDescription() ); 
		
		if (Messagebox.show("Operation can't be cancelled, press Yes to continue?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			return;
		}
		
		Reqshipfuelass rsfa = new ReqshipfuelassController().getxId(orderNumber);
		idCustomer = rsfa.getVesselnameid();
		Anayacht customer = new AnayachtController().getAnayachtxId(idCustomer);

		/*
		for (int i = 0; i < boxDetail.getListModel().getSize(); i++) {
			Object oDetail = boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
			
			Reqshipfuelassdetail reqdet = (Reqshipfuelassdetail)oDetail;
			if ( !reqdet.getStat().equalsIgnoreCase("SC") && !reqdet.getStat().equalsIgnoreCase("CC") && !reqdet.getStat().equalsIgnoreCase("IV")){
				new General().MsgBox(" Operation can't be done on current record ("+reqdet.getSeq()+"), first confirm to customer or clear refused status! ", "NFYS");
			} else if (reqdet.getStat().equalsIgnoreCase("SC") && reqdet.getConfirmcustdt() != null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) && reqdet.getTotsale()!=0 ){
				reqdet.setStat("CC"); // from SC (supplier confirmed) To CC (customer confirmed)
				new ReqshipfuelassdetailController().update(reqdet);
			} else if (reqdet.getConfirmcustdt()==null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) ){
				new General().MsgBox("No confirm date is signed on record # " + reqdet.getSeq() + ", print cancelled", "NFYS");
			} else if (reqdet.getConfirmcustdt()==null && ( reqdet.getRefused()!=null && reqdet.getRefused()==true ) ){
				new General().MsgBox("Request(s) cancelled ", "NFYS");
			} else if (reqdet.getTotsale() == 0 || ( reqdet.getCustum()==null || reqdet.getCustum().isEmpty() ) ) {
				new General().MsgBox("You can't confirm to customer: customer section is not completed! (record # "+reqdet.getSeq()+")", "NFYS");
			}
			boxDetail.invalidate(); // to refresh listbox
		}
		*/
		

		if (Messagebox.show("Do you want to print Customer confirmation ?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) == Messagebox.YES){
			
			for (int i = 0; i < boxDetail.getListModel().getSize(); i++) {
				Object oDetail = boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
				Reqshipfuelassdetail reqdet = (Reqshipfuelassdetail)oDetail;
				
				if ( !reqdet.getStat().equalsIgnoreCase("SC") && !reqdet.getStat().equalsIgnoreCase("CC") && !reqdet.getStat().equalsIgnoreCase("IV")){
					new General().MsgBox(" Operation can't be done on current record ("+reqdet.getSeq()+"), first confirm to customer or clear refused status! ", "NFYS");
				} else if (reqdet.getConfirmcustdt()==null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) ){
					new General().MsgBox("No confirm date is signed on record # " + reqdet.getSeq() + ", print cancelled", "NFYS");
				} else if (reqdet.getQuoteyesno()==null || reqdet.getQuoteyesno()==false ){
					new General().MsgBox("No quoted is signed on record # " + reqdet.getSeq() + ", print cancelled", "NFYS");
				} else if (reqdet.getConfirmcustdt()==null && ( reqdet.getRefused()!=null && reqdet.getRefused()==true ) ){
					new General().MsgBox("Request(s) cancelled ", "NFYS");
				} else if (reqdet.getTotsale() == 0 || ( reqdet.getCustum()==null || reqdet.getCustum().isEmpty() ) ) {
					new General().MsgBox("You can't confirm to customer: customer section is not completed! (record # "+reqdet.getSeq()+")", "NFYS");
				} else if (reqdet.getStat().equalsIgnoreCase("SC") && reqdet.getConfirmcustdt() != null && ( reqdet.getRefused()==null || reqdet.getRefused()==false ) && reqdet.getTotsale()!=0 ){
					
					
					reqdet.setStat("CC"); // from SC (supplier confirmed) To CC (customer confirmed)
					new ReqshipfuelassdetailController().update(reqdet);
					
					Custinvoice[] custinvoices = new CustinvoiceController().get(orderNumber, idCustomer);
									
					Integer recNumForDetail = null;
					
					// new hipotetical invoice, master record
					if (custinvoices.length==0){
						Custinvoice custInv = new Custinvoice();
						custInv.setCustid(idCustomer);
						custInv.setCustname(rsfa.getVesselname());
						custInv.setOrder(orderNumber);
						custInv.setCreditterms(customer.getPayment());
						custInv.setCurr(reqdet.getCurr());
						custInv.setDeliverydt(rsfa.getDeliverydt());
						custInv.setPorttoref(rsfa.getPorttoref());
						custInv.setPortid(rsfa.getIdportref());
						custInv.setExchangerate(rsfa.getExchrate());
						custInv.setInvoicedtreg( General.date2SqlTimestamp( new java.util.Date() ) );
						
						if (!customer.getPayment().equalsIgnoreCase("E.O.M.")){
							Timestamp tmpTimeStamp = new Timestamp( rsfa.getDeliverydt().getTime() ); 
							Calendar cal = Calendar.getInstance();
							cal.setTime(tmpTimeStamp);
							Payment payment = new PaymentsController().getPaymentxTerms(customer.getPayment());
							if (payment==null){
								payment = new Payment();
							}
							if (payment.getId()==0){
								payment.setDd(0);
							} 
							cal.add(Calendar.DAY_OF_WEEK, payment.getDd());
							tmpTimeStamp.setTime(cal.getTime().getTime());
							custInv.setDuedate(tmpTimeStamp);
						} else {
							// E.O.M
							Timestamp tmpTimeStamp = rsfa.getDeliverydt();
							Calendar cal = Calendar.getInstance();
							cal.setTime(tmpTimeStamp);
							//cal.add(Calendar.DAY_OF_WEEK, payment.getDd());
							cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));						
							tmpTimeStamp.setTime(cal.getTime().getTime());
							custInv.setDuedate(tmpTimeStamp);
						}
						custInv.setVatyesno(reqdet.getVatyesno());
						custInv.setStat("HI");
						custInv.setType("A"); // automatic invoice
						custInv.setArt15(rsfa.getArt15());
						custInv.setDtUp( General.date2SqlTimestamp( new java.util.Date() ) );
						
	
						custInv = new CustinvoiceController().add(custInv);
						recNumForDetail = custInv.getRecnum();
					} else { // take the first invoice
						Custinvoice custInvoice = custinvoices[0];
						recNumForDetail = custInvoice.getRecnum();
					}
									
					// hipotetical invoice detail record
					
					
					Custinvoicedetail[] custInvoiceDetails = new CustinvoicedetailController().get(orderNumber, idCustomer, reqdet.getSeq() );
					
					Custinvoicedetail custinvoicedetail = new Custinvoicedetail();
					
					
					if (custInvoiceDetails.length>0){
						custinvoicedetail = custInvoiceDetails[0];
					}
					
					custinvoicedetail.setRecnum(recNumForDetail);
					custinvoicedetail.setOrder(orderNumber);
					custinvoicedetail.setSeq(reqdet.getSeq());
					custinvoicedetail.setProductname(reqdet.getProductname());
					custinvoicedetail.setPartno( General.limitaString(reqdet.getPartno(), 20) );
					custinvoicedetail.setProductid(reqdet.getProductid());		
					custinvoicedetail.setQuantity(reqdet.getCustqtyquote());
					custinvoicedetail.setUnitprice(reqdet.getPrreqvess());
					custinvoicedetail.setTotalamount(reqdet.getTotsale());
					custinvoicedetail.setCustname(rsfa.getVesselname());
					custinvoicedetail.setCustid(rsfa.getVesselnameid());
					custinvoicedetail.setCurr(reqdet.getCurr());
					custinvoicedetail.setUm(reqdet.getCustum());
					custinvoicedetail.setStat("HI"); // invoice hipotetic status
					custinvoicedetail.setType("A");
					custinvoicedetail.setCustvatperc(reqdet.getCustvatperc());
					custinvoicedetail.setCustvat(reqdet.getCustvat());
					custinvoicedetail.setCusttaxed(reqdet.getCustnetcost());
					custinvoicedetail.setCusttotsalevat(reqdet.getCusttotsalevat());				
					
					if (custInvoiceDetails.length>0){
						new CustinvoicedetailController().update(custinvoicedetail);
					} else {
						new CustinvoicedetailController().add(custinvoicedetail);
					}
					
				}
				
			}
			
			boxDetail.invalidate(); // to refresh listbox
			
			try {
				printConfirmationToCustomer(orderNumber, idCustomer);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (JRException e) {
				e.printStackTrace();
			}
			
		} else {
			new General().MsgBox("You will be able to obtain print confirmation later!", "NFYS");
		}
		
	}

	
	private void printConfirmationToCustomer(Integer numOrder, Integer idCustomer) throws SQLException, JRException, FileNotFoundException {

		
		Sessions.getCurrent().setAttribute("richiestaData", null);
		
		Window finestraReqDate = (Window) Executions.createComponents(
				"/richiestaData.zul", null, null);
		finestraReqDate.doModal();
		
		Date data = (Date) Sessions.getCurrent().getAttribute("richiestaData");
		if (data==null){
			return;
		}
		
		Sessions.getCurrent().setAttribute("richiestaData", null);
		
		
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props);
		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		//params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );
		params.put( "PAR_REQUEST_ID", numOrder );
		params.put( "PAR_SUPPLIER_ID", idCustomer );
		params.put("SUBREPORT_DIR", new General().percorsoFincati() + "/");
		params.put( "PAR_DATA", data);

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/ConfirmToCustomer.jasper";
		//System.out.println(fileJasper);
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/ConfirmToCustomer.pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");
	}
	
	
}
